Ala*_*anH 15 python list insert
在JavaScript中,我可以使用splice将多个元素的数组插入到数组中:myArray.splice(insertIndex, removeNElements, ...insertThese)
但我似乎无法在没有 concat列表的情况下找到在Python中执行类似操作的方法.有这样的方式吗?
例如myList = [1, 2, 3],我想otherList = [4, 5, 6]通过调用myList.someMethod(1, otherList)get 来插入[1, 4, 5, 6, 2, 3]
mgi*_*son 35
要扩展列表,您只需使用list.extend.要从索引中的任何iterable插入元素,可以使用切片赋值...
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[5:5] = range(3)
>>> a
[0, 1, 2, 3, 4, 0, 1, 2, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)
Python 列表没有这样的方法。这是一个辅助函数,它接受两个列表并将第二个列表放入指定位置的第一个列表中:
def insert_position(position, list1, list2):
return list1[:position] + list2 + list1[position:]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19391 次 |
| 最近记录: |