为什么我不能在Python列表中插入? [英] Why I cannot make an insert to Python list?
问题描述
我正在尝试通过索引将某些项目插入现有列表,如下所示:
I'm trying to insert some item by index to existing list like this:
c = ['545646', 'text_item', '151561'].insert(1, '555')
print(c)
结果是我什么也没有.
And I'm getting None in result.
为什么我不能在Python列表中插入?
Why I cannot make an insert to the Python list?
所需的输出是:
['545646', '555', 'text_item', '151561']
推荐答案
根据Python约定,所有 muting 函数均返回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中),有一个关于 walrus运算符的建议可以缩短此时间:
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')
尽管我相信Pythonista会对此皱眉:)
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列表中插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!