Iterate Across Columns in a List of Lists in Python

时光怂恿深爱的人放手 提交于 2019-12-11 01:28:53

问题


When I attempt iteration across columns in a row, the column does no change within a nested loop:

i_rows = 4
i_cols = 3
matrix = [[0 for c in xrange(i_cols)] for r in xrange(i_rows)]

for row, r in enumerate(matrix):
    for col, c in enumerate(r):
        r[c] = 1

print matrix

Observed output

[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]

Expected output

[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]

I have tried different expressions such as xrange() and len() and I am considering switching to numpy. I am a bit surprised that a two-dimensional array in Python is not so intuitive as my first impression of the language.

The goal is a two-dimensional array with varying integer values, which I later need to parse to represent 2D graphics on the screen.

How can I iterate across columns in a list of lists?


回答1:


You just have to assign the value against the col, not c

for row, r in enumerate(matrix):
    for col, c in enumerate(r):
        r[col] = 1               # Note `col`, not `c`

Because the first value returned by enumerate will be the index and the second value will be the actual value itself.



来源:https://stackoverflow.com/questions/36281219/iterate-across-columns-in-a-list-of-lists-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!