久久久久久久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 列表中的元素)
主站蜘蛛池模板: 久在草| 欧美一区二区三区精品免费 | 日韩欧美大片在线观看 | 亚洲精品自在在线观看 | 精品日韩一区二区 | 久久久女女女女999久久 | 视频一区在线观看 | 久久大陆 | 日韩一区av | 久久久精品视频一区二区三区 | 播放一级黄色片 | 玖玖综合在线 | 蜜月va乱码一区二区三区 | 好好的日在线视频 | 综合久久99 | 在线看亚洲 | 久久国产免费看 | 国产一区二区三区亚洲 | 成人免费小视频 | 成人黄色av网站 | 日韩久久久久久久久久久 | 久久久免费在线观看 | 久久久久一区二区三区四区 | 国产传媒视频在线观看 | 国产精品不卡一区 | 中文字幕视频在线观看 | 中文字幕免费中文 | 毛片高清| 色婷婷综合在线观看 | 国产一在线观看 | a免费视频 | 亚洲精品久久久蜜桃 | 成人夜晚看av | 999国产精品视频免费 | 免费电影av | 日韩福利在线观看 | 中文字幕在线观看一区 | 精品久久久久久亚洲国产800 | 91精品久久久久久久久久入口 | 亚洲va欧美va人人爽午夜 | 少妇一级淫片aaaaaaaaa |