简体   繁体   中英

'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. This works though:

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

I want to end with col_nums = [1, 1, 1] . It doesn't seem like I'm iterating over any integers, just rows , which is a list. 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 . That's a type mismatch. Try one of these alternatives.

  1. Use append to add a single item to a list.

     for rows in board: col_nums.append(rows[col]) 
  2. You can add a list onto another 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.

     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. 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

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

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

Now, col_nums will be

[1, 1, 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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