在Python的列表列表中跨列迭代 [英] Iterate Across Columns in a List of Lists in Python

查看:128
本文介绍了在Python的列表列表中跨列迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在一行中的各列之间进行迭代时,该列在嵌套循环内没有变化:

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

观察到的输出

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

预期输出

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

我尝试了不同的表达式,例如xrange()len(),并且我正在考虑切换到numpy.我对Python中的二维数组不像我对语言的第一印象那么直观感到惊讶.

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.

目标是具有可变整数值的二维数组,我稍后需要解析该二维数组以表示屏幕上的2D图形.

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?

推荐答案

您只需要针对col而不是c

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

因为enumerate返回的第一个值将是索引,第二个值将是实际值本身.

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

这篇关于在Python的列表列表中跨列迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆