問題描述
我正在尋找最 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模板網!