【问题标题】:'int' object is not iterable for list of lists'int' 对象对于列表列表不可迭代
【发布时间】:2014-02-14 02:32:44
【问题描述】:

我遇到了一个我无法解释的错误。代码如下:

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

这给出了 'int' object is not iterable 错误。 这虽然有效:

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

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

【问题讨论】:

    标签: python list iteration


    【解决方案1】:

    当您编写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]
      

    【讨论】:

    • 我很惊讶我没有看到。谢谢
    【解决方案2】:
    board = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
    
    col = 0
    
    col_nums = list(zip(*board)[col])
    # [1, 1, 1]
    

    【讨论】:

    • 哇,一个很酷的解决方案,但它会不会有性能问题,因为zip(*board) 生成了另外两个不需要的列表?
    • 不知道 qwr 正在开发的软件系统,也不知道这个 sn-p 是如何在其中使用的,我不能说是什么问题。
    【解决方案3】:

    您的代码的问题是 rows[col] 是 int 类型,而 col_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]
    

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 2019-12-03
      • 2022-01-20
      • 2014-04-26
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      相关资源
      最近更新 更多