如何从列表中删除第一项?

[0, 1, 2, 3]   →   [1, 2, 3]

当前回答

这对我来说是有效的,而不是像下面这样使用pop,这当然会是0,因为pop的结果/返回值

>>> x = [0, 1, 2, 3].pop(0)
>>> x
0

使用下面的方法将跳过第一个值:

>>> x = [0, 1, 2, 3][1:]
>>> x
[1, 2, 3]

其他回答

使用列表切片,请参阅Python关于列表的教程了解更多详细信息:

>>> l = [0, 1, 2, 3, 4]
>>> l[1:]
[1, 2, 3, 4]
>>> x = [0, 1, 2, 3, 4]
>>> x.pop(0)
0

这里有更多。

有一种数据结构叫做双端队列或双端队列,它比列表更快更有效。您可以使用您的列表并将其转换为deque并在其中执行所需的转换。你也可以将deque转换回list。

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还提供了非常有用的函数,如将元素插入到列表的任意一侧或任何特定的索引中。您还可以旋转或反转deque。试试吧!

你会这样做

l = [0, 1, 2, 3, 4]
l.pop(0)

Or l = l[1:]

利与弊

使用pop可以检索值

假设x = l.pop(0) X等于0

你可以使用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