Sea*_*ean 4 python indexing list range
N=8
f,g=4,7
indexList = range(N)
print indexList
print f, g
indexList.pop(f)
indexList.pop(g)
Run Code Online (Sandbox Code Playgroud)
在这段代码中,我收到一条错误,指出g
in 的pop索引indexList
超出范围.这是输出:
[0, 1, 2, 3, 4, 5, 6, 7]
4 7
Traceback (most recent call last):
indexList.pop(g)
IndexError: pop index out of range
Run Code Online (Sandbox Code Playgroud)
我不明白,g
有一个值为7,列表包含7个值,为什么它不能返回列表中的7?
要获得弹出列表的最终值,您可以这样做:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
请记住,pop会删除该项,并且弹出后列表会更改长度.使用负数来从可能正在改变大小的列表末尾开始索引,或者只使用不带最终项参数的pop().
由于pop可以产生这些错误,因此您经常会在异常块中看到它们:
>>> l=[]
>>> try:
... i=l.pop(5)
... except IndexError:
... print "sorry -- can't pop that"
...
sorry -- can't pop that
Run Code Online (Sandbox Code Playgroud)
弹出4后,列表只有7个值.如果您print indexList
追随您pop(f)
,它将如下所示:
[0, 1, 2, 3, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
24099 次 |
最近记录: |