我正在尝试按索引向现有列表插入一些项目,如下所示:
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模板网!
在 DataFrame 的开头(最左端)插入一列Insert a column at the beginning (leftmost end) of a DataFrame(在 DataFrame 的开头(最左端)插入一列)
Python psycopg2 没有插入到 postgresql 表中Python psycopg2 not inserting into postgresql table(Python psycopg2 没有插入到 postgresql 表中)
list extend() 索引,不仅将列表元素插入到末尾list extend() to index, inserting list elements not only to the end(list extend() 索引,不仅将列表元素插入到末尾)
如何使用 list.insert 将 Python 中的元素添加到列表How to add element in Python to the end of list using list.insert?(如何使用 list.insert 将 Python 中的元素添加到列表末尾?)
TypeError:“浮动"对象不可下标TypeError: #39;float#39; object is not subscriptable(TypeError:“浮动对象不可下标)
在每个第 n 个元素之后插入 Python 列表中的元素Insert element in Python list after every nth element(在每个第 n 个元素之后插入 Python 列表中的元素)