在 JavaScript 中,我可以使用 splice
将多个元素的数组插入到数组中:myArray.splice(insertIndex, removeNElements, ...insertThese)
。
但我似乎找不到在 Python 中做类似事情的方法没有 concat 列表。有这样的方法吗? (已经有一个关于 inserting single items 的问答,而不是多个。)
例如 myList = [1, 2, 3]
我想通过调用 myList.someMethod 插入
得到 otherList = [4, 5, 6]
(1, otherList)[1, 4, 5, 6, 2, 3]
最佳答案
要扩展列表,您只需使用list.extend
。要在索引处插入来自任何可迭代对象的元素,您可以使用切片赋值...
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[5:5] = range(10, 13)
>>> a
[0, 1, 2, 3, 4, 10, 11, 12, 5, 6, 7, 8, 9]
关于python - 如何将多个元素插入到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39541370/