简体   繁体   中英

Problem with iterating over the list of lists

I am trying to compute a transpose of the matrix, which I have in the form of list of lists. The initial matrix is m n, I have created a matrix n m. The problem appears when I start to use the nested loop.

m = 0
for i in range(0, rows):
    for j in range(0, columns):
        final1[j][i] = m
        print(final1)
        m += 1

I deliberately print the whole list of lists (final) to see how at each step my values are changing, also I just assign consequent natural numbers for simplicity. what I see is (first 4 lines of the output)

[[0, None, None, None], [0, None, None, None], [0, None, None, None]]
[[1, None, None, None], [1, None, None, None], [1, None, None, None]]
[[2, None, None, None], [2, None, None, None], [2, None, None, None]]
[[2, 3, None, None], [2, 3, None, None], [2, 3, None, None]]

So, by accessing final[j][i], at position j = 0, i = 0 the values final[1][0] and final[2][0] are also changing. How to avoid this? and make the first 4 lines of this format:

[[0, None, None, None], [None, None, None, None], [None, None, None, None]]
[[0, None, None, None], [1, None, None, None], [None, None, None, None]]
[[0, None, None, None], [1, None, None, None], [2, None, None, None]]
[[0, 3, None, None], [1, None, None, None], [2, None, None, None]]
rows = int(input())
columns = int(input())
final1 = [[None] * rows] * columns

This is the way I declare final1

This happens because the declaration statement is internally equivalent to appending a single list ([None]*rows) column times into the final1 list.

If you are familiar with copy problem , this is nearly the same. All the lists inside final1 are the same lists in terms of the memory they represent.

That's why when you update a value in one list, it gets reflected to all.

Note: You are actually creating a list of lists with column number of rows and row number of columns.

You can solve this issue by declaring final1 this way:

final1 = [[None for i in range(rows)] for j in range(columns)]

ps: I've used rows inside and columns outside just to make it as an alternative to your declaration. It still produces a list of lists with column number of rows and row number of columns

This works:

rows = int(input())
columns = int(input())
final1 = [[None for i in range(rows)] for j in range(columns)]

m = 0
for i in range(rows):
    for j in range(columns):
        final1[j][i] = m
        m += 1

print(final1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM