为什么我不能插入 Python 列表?

2022-01-09 00:00:00 python python-3.x list insert

问题描述

我正在尝试按索引向现有列表插入一些项目,如下所示:

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:]]

相关文章