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

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

当前回答

有一种数据结构叫做双端队列或双端队列,它比列表更快更有效。您可以使用您的列表并将其转换为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。试试吧!

其他回答

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

这里有更多。

你也可以使用list.remove(a[0])来弹出列表中的第一个元素。

>>>> a=[1,2,3,4,5]
>>>> a.remove(a[0])
>>>> print a
>>>> [2,3,4,5]

你可以使用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 = [0, 1, 2, 3, 4]
l.pop(0)

Or l = l[1:]

利与弊

使用pop可以检索值

假设x = l.pop(0) X等于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。试试吧!