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

list extend() 索引,不僅將列表元素插入到末尾

list extend() to index, inserting list elements not only to the end(list extend() 索引,不僅將列表元素插入到末尾)
本文介紹了list extend() 索引,不僅將列表元素插入到末尾的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我正在尋找最 Pythonic 的方式來實現列表 extend 函數的一個版本,它擴展到給定的索引而不是列表的末尾.

I'm looking for the most pythonic way to implement a version of the list extend function, where it extends to a given index instead of the end of the list.

a_list = [ "I", "rad", "list" ]                                                       
b_list = [ "am", "a" ]
a_list.my_extend( b_list, 1 ) # insert the items from b_list into a_list at index 1

print( a_list ) # would output: ['I', 'am', 'a', 'rad', 'list']

有沒有辦法在不建立新列表的情況下做到這一點,像這樣?

Is there a way to do this without building a new list, like this?

a_list = [ "I", "rad", "list" ]
b_list = [ "am", "a" ]
c_list = []

c_list.extend( a_list[:1] )
c_list.extend( b_list     )
c_list.extend( a_list[1:] )

print( c_list ) # outputs: ['I', 'am', 'a', 'rad', 'list']

這種方法實際上并沒有那么糟糕,但我有一種預感,它可能會更容易.可以嗎?

That approach isn't actually so bad, but I have a hunch it could be easier. Could it?

推薦答案

當然可以使用切片索引:

Sure, you can use slice indexing:

a_list[1:1] = b_list

為了演示一般算法,如果您要在假設的自定義 list 類中實現 my_extend 函數,它看起來像這樣:

Just to demonstrate the general algorithm, if you were to implement the my_extend function in a hypothetical custom list class, it would look like this:

def my_extend(self, other_list, index):
    self[index:index] = other_list

但實際上不要讓它成為一個函數,只需在需要時使用切片符號即可.

But don't actually make that a function, just use the slice notation when you need to.

這篇關于list extend() 索引,不僅將列表元素插入到末尾的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

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

相關文檔推薦

Why I cannot make an insert to Python list?(為什么我不能插入 Python 列表?)
Insert a column at the beginning (leftmost end) of a DataFrame(在 DataFrame 的開頭(最左端)插入一列)
Python psycopg2 not inserting into postgresql table(Python psycopg2 沒有插入到 postgresql 表中)
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 列表中的元素)
主站蜘蛛池模板: 免费一级黄色 | 黄色三级视频网站 | 夜夜躁狠狠躁日日躁av | 成人深夜 | 免费国产精品视频 | 欧美一区二区三区四区五区 | 午夜视频 | 91丨porny丨成人蝌蚪 | 一本伊人 | 欧美视频三区 | 白白色在线观看 | 欧美日韩中文字幕在线观看 | 在线观看a视频 | 91理论片午午伦夜理片久久 | 五月婷婷激情综合 | 美国式禁忌14在线 | 日韩免费一区 | 97国产超碰 | 亚洲国产成人av | 懂色av一区二区夜夜嗨 | 欧美在线免费 | 免费成人小视频 | 欧美精品网站 | 黄网站免费看 | 欧美一级黄色大片 | 九九视频这里只有精品 | 一区二区不卡 | 国产三级免费观看 | 色综合一区二区 | 欧美国产在线观看 | 免费av大片 | 精品亚洲一区二区三区 | 男人爱看的网站 | 成年人视频在线播放 | 综合av网 | 色综合天天综合网天天狠天天 | 亚洲精品一区二区在线观看 | 日韩一级片视频 | www.44| 欧美操操操 | 黄色三级av|