我正在編寫一個代碼,以從包含3個嵌套列表的列表中彈出。 我想彈出從第一個內部循環結束開始的最後一個元素。它工作正常,直到它到達第一個元素並返回(IndexError:從空列表中彈出)。如何使用範圍函數來處理這種情況?從空列表錯誤中彈出
toappendlst= [[[62309, 1, 2], [62309, 4, 2], [6222319, 4, 2], [6235850, 4, 2], [82396378, 4, 3], [94453486, 4, 3], [0, 0, 0]],[[16877135, 6, 2], [37247278, 7, 2], [47671207, 7, 2], [0, 0, 0]]]
for chro in range(-1,len(toappendlst)):
popdPstn = toappendlst[chro].pop()
print(popdPstn)
ø\ P
[0, 0, 0]
[47671207, 7, 2]
[37247278, 7, 2]
Traceback (most recent call last):
File "C:\Python33\trial.py", line 41, in <module>
popdPstn = toappendlst[chro].pop()
IndexError: pop from empty list
使用'範圍(LEN(toappendlst))'。更優選地,簡單地迭代列表:'for for lst in toappendlst:popdPstn = lst.pop()...' – falsetru
無法複製。你發佈的代碼打印不同的東西,並不會拋出錯誤。 –