問題描述
我正在嘗試按索引向現有列表插入一些項目,如下所示:
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 列表?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!