久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

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

Why I cannot make an insert to Python list?(為什么我不能插入 Python 列表?)
本文介紹了為什么我不能插入 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 列表?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Insert a column at the beginning (leftmost end) of a DataFrame(在 DataFrame 的開頭(最左端)插入一列)
Python psycopg2 not inserting into postgresql table(Python psycopg2 沒有插入到 postgresql 表中)
list extend() to index, inserting list elements not only to the end(list extend() 索引,不僅將列表元素插入到末尾)
How to add element in Python to the end of list using list.insert?(如何使用 list.insert 將 Python 中的元素添加到列表末尾?)
TypeError: #39;float#39; object is not subscriptable(TypeError:“浮動對象不可下標)
Insert element in Python list after every nth element(在每個第 n 個元素之后插入 Python 列表中的元素)
主站蜘蛛池模板: 成人精品在线视频 | 日中文字幕在线 | 欧美日韩成人在线观看 | 亚洲视频一区在线观看 | 国产成人久久精品一区二区三区 | 亚洲精品一级 | 欧美激情视频网站 | 国产一区二区精品在线观看 | 国产激情一区二区三区 | 国产成人亚洲精品 | 精品99在线 | 国产一区欧美一区 | 国产成人麻豆免费观看 | 中文在线一区二区 | 亚洲在线视频 | 成人性视频免费网站 | av一级久久| 亚洲一区二区精品视频 | 一本一道久久a久久精品综合蜜臀 | 国内精品一区二区三区 | 91社区在线观看播放 | 国产在线观看免费 | 欧美一区二区 | 久久国产精品免费视频 | 国产精品日韩欧美一区二区三区 | 欧美三级视频在线观看 | 黄色免费网 | 天天射天天干 | 青青草视频网站 | 久日精品| 免费看欧美一级片 | 日韩三区 | 激情毛片 | 亚洲啊v | 欧美成人免费在线视频 | 国产在线对白 | 日韩快播电影网 | 精品粉嫩aⅴ一区二区三区四区 | 一区二区在线视频 | 国产精品性做久久久久久 | 日韩av资源站 |