如何从列表中删除第一个项?
[0, 1, 2, 3] → [1, 2, 3]
你可以在这里找到一些有用的列表函数。
>>> l = ['a', 'b', 'c', 'd']
>>> l.pop(0)
'a'
>>> l
['b', 'c', 'd']
>>>
>>> l = ['a', 'b', 'c', 'd']
>>> del l[0]
>>> l
['b', 'c', 'd']
>>>
这两种方法都会修改你的原始列表。
其他人建议使用切片:
此外,如果你要执行多个pop(0)
操作,应该考虑使用collections.deque
。
from collections import deque
>>> l = deque(['a', 'b', 'c', 'd'])
>>> l.popleft()
'a'
>>> l
deque(['b', 'c', 'd'])
切片:
x = [0,1,2,3,4]
x = x[1:]
这将返回原始数据的子集,但不会修改它。
x
是空的,x=x[1:]
会让它保持为空而不报错。但是,对于一个空列表 x
,x.pop(0)
会抛出异常。有时候抛出异常是我们想要的:如果假设列表中至少有一个元素是错误的,我们可能希望得到通知。 - ead你只需要这样做
l = [0, 1, 2, 3, 4]
l.pop(0)
或者 l = l[1:]
优缺点
使用pop可以检索值
例如 x = l.pop(0)
,x
将是0
x = [0, 1, 2, 3, 4]
del x[0]
print x
# [1, 2, 3, 4]
x[1:]
不会保留原始对象,但可能更快。如果删除的对象应该进入垃圾回收器,则不需要使用pop(0)
。 - B.R.您可以使用如PEP 3132中所述的解包赋值。
您应该尝试像以下这样进行解包:
>>> l = [0, 1, 2, 3, 4]
>>> _, *l = l
>>> l
[1, 2, 3, 4]
正如在PEP 3132中提到的:
This PEP proposes a change to iterable unpacking syntax, allowing to specify a "catch-all" name which will be assigned a list of all items not assigned to a "regular" name.
An example says more than a thousand words:
>>> a, *b, c = range(5) >>> a 0 >>> c 4 >>> b [1, 2, 3]
pop(0)
相比性能的额外信息?非常感谢。 - Wolf你也可以使用 list.remove(a[0])
来从列表中弹出第一个元素。
>>>> a=[1,2,3,4,5]
>>>> a.remove(a[0])
>>>> print a
>>>> [2,3,4,5]
a.remove(a[1-1])
的答案呢?那也是另一种方式。 - Ned Batchelderlist.remove(a[i])
来移除第i个元素。对于重复的值,它可能会找到一个较早的具有相同值的元素,而删除那个元素而不是第i个元素。 - Ned Batchelder有一种叫做deque
或双端队列的数据结构比列表更快更高效。您可以使用自己的列表并将其转换为deque,然后对其中所需的转换进行操作。 您也可以将deque转换回列表。
import collections
mylist = [0, 1, 2, 3, 4]
#make a deque from your list
de = collections.deque(mylist)
#you can remove from a deque from either left side or right side
de.popleft()
print(de)
#you can covert the deque back to list
mylist = list(de)
print(mylist)
Deque提供了非常有用的函数,例如在列表的任一侧或任何特定索引处插入元素。您还可以旋转或反转双端队列。试试吧!
list.reverse()
来反转列表,然后使用list.pop()
来移除最后一个元素,例如:l = [0, 1, 2, 3, 4]
l.reverse()
print l
[4, 3, 2, 1, 0]
l.pop()
0
l.pop()
1
l.pop()
2
l.pop()
3
l.pop()
4
l.pop(0)
呢?在使用 l.pop()
后,你忘记了进行 l.reverse()
。你的解决方案性能不佳。 - Christoph S.
pop(0)
时所需的时间从1分31秒降低到了200-250毫秒,而使用deque
后能够实现此效果。非常感谢。 - Christoph S.