从空列表弹出错误
我正在写一段代码,目的是从一个包含三个嵌套列表的列表中删除元素。
我想从第一个内部循环的末尾开始删除最后一个元素。这个过程一直很顺利,直到它到达第一个元素时,就会出现一个错误(IndexError: pop from empty list),意思是试图从空列表中删除元素。
我该如何使用范围函数来处理这种情况呢?
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)
O\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
2 个回答
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
你在用 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)))
。