如何从列表中删除第一个项目? [英] How to remove the first Item from a list?

查看:30
本文介绍了如何从列表中删除第一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有列表 [0, 1, 2, 3, 4] 我想把它变成 [1, 2, 3, 4].我该怎么做?

解决方案

您可以找到一个简短的有用列表函数集合 此处.

list.pop(index)

<预><代码>>>>l = ['a', 'b', 'c', 'd']>>>l.pop(0)'一种'>>>升['b', 'c', 'd']>>>

del list[index]

<预><代码>>>>l = ['a', 'b', 'c', 'd']>>>德尔 l[0]>>>升['b', 'c', 'd']>>>

这些都会修改您的原始列表.

其他人建议使用切片:

  • 复制列表
  • 可以返回一个子集

此外,如果您正在执行许多 pop(0),您应该查看 collections.deque

from collections import deque>>>l = deque(['a', 'b', 'c', 'd'])>>>l.popleft()'一种'>>>升deque(['b', 'c', 'd'])

  • 提供从列表左端弹出的更高性能

I have the list [0, 1, 2, 3, 4] I'd like to make it into [1, 2, 3, 4]. How do I go about this?

解决方案

You can find a short collection of useful list functions here.

list.pop(index)

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

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

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

这篇关于如何从列表中删除第一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆