Why I cannot make an insert to Python list?(为什么我不能插入 Python 列表?)
问题描述
我正在尝试按索引向现有列表插入一些项目,如下所示:
I'm trying to insert some item by index to existing list like this:
c = ['545646', 'text_item', '151561'].insert(1, '555')
print(c)
我得到的结果是 None .
And I'm getting None in result.
为什么我不能插入 Python 列表?
Why I cannot make an insert to the Python list?
需要的输出是:
['545646', '555', 'text_item', '151561']
推荐答案
根据 Python 约定,所有 mutating 函数都返回 None.Nonmutating 函数返回新值.insert 是一个变异函数(改变它操作的对象),所以它返回 None;然后将其分配给 c.
By Python convention, all mutating functions return None. Nonmutating functions return the new value. insert is a mutating function (changes the object it operates on), so it returns None; you then assign it to c.
事实上,在当前的 Python 中,没有办法在一条语句中做到这一点.在未来(几乎可以肯定在 Python 3.8 中),有一个关于 海象运算符的提议 这将允许你缩短这个:
In fact, there is no way to do this in one statement in current Python. In the future (almost certainly in Python 3.8), there is a proposal for a walrus operator that will allow you to shorten this:
(c := ['545646', 'text_item', '151561']).insert(1, '555')
虽然我相信 Pythonistas 会对此皱眉头:)
though I believe Pythonistas will frown on it :)
随着评论中的问题,如何将插入作为表达式?最简单的方法是定义另一个函数;例如:
With the question in the comments, how to do an insert as an expression? The easiest way is to define another function; for example:
def insert_and_return_list(lst, pos, val):
lst.insert(pos, val)
return lst
c = insert_and_return_list(['545646', 'text_item', '151561'], 1, '555')
您也可以完全避免 insert,而使用切片和 splats:
You could also avoid insert altogether, and use slices and splats:
[*lst[:1], '555', *lst[2:]]
这篇关于为什么我不能插入 Python 列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能插入 Python 列表?
基础教程推荐
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
