如何在列表中插入多个元素?

2024-03-29 13:03:03 发布

您现在位置:Python中文网/ 问答频道 /正文

在JavaScript中,我可以使用splice将多个元素的数组插入到数组中:myArray.splice(insertIndex, removeNElements, ...insertThese)

但是如果没有concat列表,我似乎找不到在Python中执行类似操作的方法。有这种方法吗?

例如myList = [1, 2, 3],我想通过调用myList.someMethod(1, otherList)来插入otherList = [4, 5, 6],以获得[1, 4, 5, 6, 2, 3]


Tags: 方法元素列表数组javascriptconcatsplicemylist
2条回答

Python列表没有这样的方法。下面是helper函数,它接受两个列表并将第二个列表放入第一个列表的指定位置:

def insert_position(position, list1, list2):
    return list1[:position] + list2 + list1[position:]

要扩展列表,只需使用list.extend。要在索引处插入任何iterable中的元素,可以使用slice赋值。。。

>>> 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]

相关问题 更多 >