要获取弹出列表的最终值,您可以这样做:
>>> l=range(8)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7]
>>> l.pop(4) # item at index 4
4
>>> l
[0, 1, 2, 3, 5, 6, 7]
>>> l.pop(-1) # item at end - equivalent to pop()
7
>>> l
[0, 1, 2, 3, 5, 6]
>>> l.pop(-2) # one left of the end
5
>>> l
[0, 1, 2, 3, 6]
>>> l.pop() # always the end item
6
>>> l
[0, 1, 2, 3]
请记住pop http://docs.python.org/tutorial/datastructures.html#more-on-lists删除项目,并且列表在弹出后改变长度。使用负数从大小可能发生变化的列表末尾开始索引,或者仅使用不带参数的 pop() 作为结束项。
由于 pop 可能会产生这些错误,因此您经常会在异常块 http://docs.python.org/reference/compound_stmts.html#try:
>>> l=[]
>>> try:
... i=l.pop(5)
... except IndexError:
... print "sorry -- can't pop that"
...
sorry -- can't pop that