2014-02-14 60 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正在處理或如何使用此片段,我不能說什麼構成問題。 –