Iterate over columns in a list of lists in Python

When I try to iterate through the columns in a row, the column does not change inside the 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 Conclusion

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

Expected Result

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

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

The goal is a two-dimensional array with variable integer values, which I later need to analyze in order to present 2D graphics on the screen.

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

+1
source share
1 answer

You just need to assign a value to col , not c

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

Since the first value returned by enumerate will be the index, and the second value will be the actual value.

+1
source

Source: https://habr.com/ru/post/1268541/


All Articles