列出extend()以建立索引,不仅将列表元素插入到末尾 [英] list extend() to index, inserting list elements not only to the end

查看:80
本文介绍了列出extend()以建立索引,不仅将列表元素插入到末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找实现列表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.

这篇关于列出extend()以建立索引,不仅将列表元素插入到末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆