我需要在 時采取行動pole[i][j] == 1,但它會引發錯誤:
型別錯誤:串列索引必須是整數或切片,而不是串列
pole = [[0,1,0],
[1,0,1],
[0,1,1]]
for i in pole:
for j in pole:
if pole[i][j] == 1:
my_code()
uj5u.com熱心網友回復:
您使用for i in polewhich 獲取pole不是索引的實際值。這是更正后的代碼:
pole = [[0,1,0],
[1,0,1],
[0,1,1]]
for i in range(len(pole)):
for j in range(len(pole[i])):
if pole[i][j] == 1:
my_code()
或者,您可以使用值而不是索引,因此:
pole = [[0,1,0],
[1,0,1],
[0,1,1]]
for i in pole:
for j in i:
if j == 1:
my_code()
uj5u.com熱心網友回復:
for-in 回圈遍歷串列的元素,而不是它的索引。另外,請注意您的內回圈執行與外回圈相同的迭代,而不是迭代子串列:
for x in pole:
for y in x:
if y == 1:
my_code()
uj5u.com熱心網友回復:
好吧,從技術上講,鑒于my_code()不使用ior j,您可以執行以下操作:
for _ in range(sum(map(sum, pole))):
my_code()
極點中的元素不一定需要為 0 和 1 - 您可以觸發其他條件,例如:
sum(map(lambda x: sum(y > 0 for y in x), pole)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/385129.html
