开发者

list extend() to index, inserting list elements not only to the end

I'm looking for the most pythonic way to implement a version of the list extend function, wh开发者_运维技巧ere 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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜