2014-02-14 41 views
1

我遇到了一个我无法解释的错误。以下是代码:'int'对象不能迭代列表列表

board = [[1, 2, 3],[1, 2, 3],[1, 2, 3]] 
col = 0 
col_nums = [] 
for rows in board: 
    col_nums += rows[col] 

这给出'int'对象不是可迭代错误。 这工作虽然:

for rows in board: 
    print(rows[col]) 

我想col_nums = [1, 1, 1]结束。它似乎并没有迭代任何整数,只是rows,这是一个列表。我认为这可能与+=有关。

回答

3

当您编写col_nums += rows[col]时,您正试图在list上添加一个int。这是一种类型不匹配。尝试这些替代方法之一。

  1. 使用append将单个项目添加到列表中。

    for rows in board: 
        col_nums.append(rows[col]) 
    
  2. 您可以添加list到另一个list

    for rows in board: 
        col_nums += [rows[col]] 
    
  3. 一起extend调用一次添加的所有项目替换整个循环。

    col_nums.extend(rows[col] for rows in board) 
    
  4. 用列表理解一举创建列表。

    col_nums = [rows[col] for rows in board] 
    
+0

我很惊讶,我没有看到这一点。谢谢 – qwr

1

与您的代码的问题是,rows[col]int型的,而col_nums是一个列表。你可以用[]检查,像这样

for rows in board: 
    print(type(col_nums), type(rows[col])) 

将打印由INT元素转换到一个列表

(<type 'list'>, <type 'int'>) 

可以解决这个问题,通过周围,像这样

col_nums += [rows[col]] 

但是,如果你只想得到所有子列表中的第一个元素,最好和惯用的方法是使用operator.itemgetter

from operator import itemgetter 
get_first_element = itemgetter(0) 
col_nums = map(get_first_element, board) 

现在,col_nums

[1, 1, 1] 
3
board = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] 

col = 0 

col_nums = list(zip(*board)[col]) 
# [1, 1, 1] 
+0

哇,一个很酷的解决方案,但它会有一个性能问题,因为zip(* board)生成了另外两个不需要的列表? – WKPlus

+0

不知道任何关于软件系统qwr正在处理或如何使用此片段,我不能说什么构成问题。 –