繁体   English   中英

'int'对象不可用于列表列表

[英]'int' object is not iterable for list of lists

我遇到了无法完全解释的错误。 这是代码:

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这是一个列表。 我认为这可能与+=

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

  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] 
board = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

col = 0

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

您的代码的问题在于, rows[col]的类型为intcol_nums是一个列表。 你可以这样检查

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

将打印

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

您可以通过用[]括起来将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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM