2014-03-03 35 views
-3

我正在編寫一個代碼,以從包含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 
+0

使用'範圍(LEN(toappendlst))'。更優選地,簡單地迭代列表:'for for lst in toappendlst:popdPstn = lst.pop()...' – falsetru

+0

無法複製。你發佈的代碼打印不同的東西,並不會拋出錯誤。 –

回答

0

你迭代在range(-1, len(lst)),這是len(lst)+1編號(-1至len(lst)-1含)的範圍內。這比列表中的元素數量多,因此您的最終.pop在空列表上運行。

您可能不需要從列表中實際彈出。例如,for item in reversed(lst):將以相反的順序(與彈出列表的順序相同)遍歷列表,而不會破壞列表內容。或者,如果您確實需要將每個項目從列表中彈出,則只需迭代for i in xrange(len(lst))即可迭代len(lst)次。如果您需要相反的順序,for i in reversed(xrange(len(lst)))

+0

謝謝@nneonneo ..我已經修復了第一個案例。我不必從(-1)開始。我需要彈出,因爲toappendlst是輸入列表,我要將彈出的值插入到outerlst ..我已經做了處理這種情況是添加一個while循環。 outerlst = [] 有效範圍內的CHROM(LEN(toappendlst)): outerlst.append([]) 而(LEN(toappendlst [CHROM])> 0): popdPstn = toappendlst [CHROM] .pop() – user91

0

改變你的清單與....

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]]] 

,或者您可以使用列表像一個序列...

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 toappendlst[::-1]: 
     print(chro) 
+0

我不必玩清單,因爲這只是一個測試列表,但我會從一個txt文件輸入。 – user91

+0

確定然後** toappendlst [:: - 1] **正在爲您的列表。 –

+0

它確實有效。謝謝@ajay。這對我來說是新的。 – user91