簡體   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