简体   繁体   English

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

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

I've run into an error that I can't quite explain. 我遇到了无法完全解释的错误。 Here is the code: 这是代码:

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

This gives 'int' object is not iterable error. 这给出了“ int”对象不可迭代的错误。 This works though: 这可以工作:

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

I want to end with col_nums = [1, 1, 1] . 我想以col_nums = [1, 1, 1]结尾。 It doesn't seem like I'm iterating over any integers, just rows , which is a list. 似乎我没有在遍历任何整数,而只是在rows这是一个列表。 I think it might have something to do with += . 我认为这可能与+=

When you write col_nums += rows[col] you're trying to add an int onto a list . 当您编写col_nums += rows[col]您试图将一个int添加到list That's a type mismatch. 这是类型不匹配。 Try one of these alternatives. 尝试这些替代方法之一。

  1. Use append to add a single item to a list. 使用append将单个项目添加到列表。

     for rows in board: col_nums.append(rows[col]) 
  2. You can add a list onto another list . 您可以将一个list添加到另一个list

     for rows in board: col_nums += [rows[col]] 
  3. Replace the entire loop with a call to extend to add all the items at once. 用调用替换整个循环以extend以一次添加所有项。

     col_nums.extend(rows[col] for rows in board) 
  4. Create the list in one fell swoop with a list comprehension. 借助列表理解功能一次即可创建列表。

     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]

The problem with your code is that rows[col] is of type int whereas col_nums is a list. 您的代码的问题在于, rows[col]的类型为intcol_nums是一个列表。 You can check that like this 你可以这样检查

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

will print 将打印

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

You can fix this problem by converting the int element to a list by surrounding that with [] , like this 您可以通过用[]括起来将int元素转换为列表来解决此问题,如下所示

col_nums += [rows[col]]

But, if you want to get only the first elements of all the sublists, the best and idiomatic way would be to use operator.itemgetter 但是,如果只想获得所有子列表的第一个元素,那么最好的惯用方法是使用operator.itemgetter

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

Now, col_nums will be 现在, col_nums将是

[1, 1, 1]

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

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