2014-03-03 37 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