Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

python - 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, 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...