Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

python - I append to every items in my list at once instead of one at a time, Character Picture Grid


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The key to the problem is in these two lines:

def transpose(heart):
    outcome = []
    row = [] # <- Key1
    for i in range(len(heart[0])):
        outcome = outcome + [row] # <- Key2
    for i in range(len(outcome)):
        for y in range(len(heart)):
            outcome[i].append(heart[y][i])
    for i in outcome:
        print(i)

What you are creating in the "Key 2" line is a list of references to the list named row. So any time you call append on any item of the list "outcome" the "row" list appends a new item. Which is the reason of the bad output. In the second example you are initializing each item of "outcome" as a different empty list

To see the error more clearly you can run the following code:

outcome = []
row = ["Hello! I'm the row list",] 
for i in range(5):
     outcome = outcome + [row]
print(outcome)

A simple way to fix it would be to substitute row by an empty list

outcome = []
for i in range(5):
     outcome = outcome + [[]]
outcome[0].append('I am The first item')
outcome[2].append('I am The Third item')
print(outcome)

Edit: fixed typos


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...