Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

python - 如何从列表中删除第一个项目?(How to remove the first Item from a list?)

I have the list [0, 1, 2, 3, 4] I'd like to make it into [1, 2, 3, 4] . (我有列表[0, 1, 2, 3, 4]我想把它变成[1, 2, 3, 4] 。) How do I go about this? (我该怎么做?)

  ask by rectangletangle translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Python List (Python列表)

list.pop(index) (list.pop(指数))

>>> l = ['a', 'b', 'c', 'd']
>>> l.pop(0)
'a'
>>> l
['b', 'c', 'd']
>>> 

del list[index] (del list [index])

>>> l = ['a', 'b', 'c', 'd']
>>> del l[0]
>>> l
['b', 'c', 'd']
>>> 

These both modify your original list. (这些都会修改您的原始列表。)

Others have suggested using slicing: (其他人建议使用切片:)

  • Copies the list (复制列表)
  • Can return a subset (可以返回一个子集)

Also, if you are performing many pop(0), you should look at collections.deque (此外,如果您执行许多pop(0),您应该查看collections.deque)

from collections import deque
>>> l = deque(['a', 'b', 'c', 'd'])
>>> l.popleft()
'a'
>>> l
deque(['b', 'c', 'd'])
  • Provides higher performance popping from left end of the list (从列表的左端提供更高性能的弹出)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...