久久久久久久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 列表中的元素)
主站蜘蛛池模板: 国产一区二区三区四区hd | av资源中文在线天堂 | 91精品国产高清一区二区三区 | 韩日一区二区 | 亚洲免费一区二区 | 日韩高清国产一区在线 | 国产伦精品一区二区三区照片91 | 国产成人99久久亚洲综合精品 | 一级免费毛片 | com.色.www在线观看 | av第一页 | 欧美国产精品 | 国产高清在线精品一区二区三区 | 国产精品1区2区3区 男女啪啪高潮无遮挡免费动态 | 国产精品成人国产乱一区 | 国产精品久久久久久久久免费高清 | 亚洲天堂一区 | 91精品国产乱码久久久久久久久 | 久久久一二三 | 99爱在线视频 | 国产欧美日韩在线一区 | 成人国产精品久久 | 欧美一区二区三区视频在线观看 | 久久精品国产亚洲a | 久久久精| 精品欧美乱码久久久久久 | 全免费a级毛片免费看视频免费下 | 亚洲视频一区二区三区四区 | 日韩一区二区精品 | 香蕉久久久 | 黄视频网站在线 | 午夜精品一区二区三区在线视频 | 人人澡人人射 | 91精品国产综合久久国产大片 | 国产精品性做久久久久久 | 久久久久精 | 日本a在线 | 亚洲视频一区二区三区 | 蜜桃传媒一区二区 | 欧美极品在线视频 | 久久久久久久久久久久久91 |