Python循环遍历列表获取列表索引错误

时间:2014-08-27 20:06:20

标签: python python-2.7

我有一个列表,想要遍历每一行并打印第1列中的值。我收到错误消息TypeError: list indices must be integers, not list我在这里缺少什么?

test = [[1,2,4],[3,4,3]]

for currentrow in test:
     print test[currentrow][1]

4 个答案:

答案 0 :(得分:2)

在您的示例中,currentrow将是一个列表。

所以你想做的是

test = [[1,2,4],[3,4,3]]

for currentrow in test:
    print currentrow[1]

将打印

2
4

答案 1 :(得分:1)

在Python中使用for循环时,变量currentrow将被分配列表中的实际对象,而不是索引。那么,你想要的是以下内容:

test = [[1,2,4],[3,4,3]]

for currentrow in test:
     print currentrow[1]

这种方法的好处是它也更容易阅读。

如果您希望索引在循环体中可用,则可以使用enumerate。这是一个例子:

test = [[1,2,4],[3,4,3]]

for i, currentrow in enumerate(test):
    print "Row {}: {}".format(i, currentrow[1])

答案 2 :(得分:1)

如果您尝试访问测试中每个数组中的第二个元素,那么您将采取以下措施:

test = [[1,2,4],[3,4,3]]

for currentrow in test:
    print currentrow[1]

答案 3 :(得分:0)

此处代码的问题在于,当您遍历test列表时,每个条目都是自己的列表。因此,您尝试将该条目用作索引,这是不可能的。尝试这样的事情:

for i in range(len(test)):
    print test[i][1]