2
grid = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
cages = [[9, 3, 0, 5, 6], [7, 2, 1, 2], [10, 3, 3, 8, 13], [14, 4, 4, 9, 14, 19], [3, 1, 7], [8, 3, 10, 11, 16], [13, 4, 12, 17, 21, 22], [5, 2, 15, 20], [6, 3, 18, 23, 24]]
noCages = 9
total = 0
i = 0
index = 2
while i < noCages:
while index < len(i):
total = total + grid[index/5][index%5]
print grid[index/5][index%5]
index += 1
print total
i += 1
total = 0
我試圖使用while循環來遍歷籠列表,並採取第二個元素到每個嵌套列表中的最後一個元素。然後我將這些值添加到總數中,並且我想爲所有嵌套列表執行此操作。我無法使用while循環遍歷籠子列表。我怎樣才能更好地實現這一點。 (也就是說len(i)是一個整數,沒有長度,這是有道理的,但是,我不知道如何使用它使用While循環遍歷2D列表Python使用
'而指數
你有什麼期望輸出? – danidee
不確定您是使用Python 2還是3,但在Python 3中,您不能使用[index/5]作爲列表索引,因爲這將返回一個浮點數。如果您試圖獲得籠[0] [1至4],你可以使用sum(cages [ 0] [1:5])。使用求和函數,您可以將所需列表的任何一個切片相加,而無需迭代它們。 –