list extend() to index, inserting list elements not only to the end(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() 索引,不仅将列表元素插入到末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:list extend() 索引,不仅将列表元素插入到末尾
基础教程推荐
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
