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

2022-11-02Python开发问题
12

本文介绍了为什么我不能插入 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 列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11