python - 如何将多个元素插入到列表中?

标签 python list insert

在 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/

相关文章:

python - 使用Python递归替换字符串中的字符

json - R:将具有空元素的嵌套列表转换为 data.frame(来自 json)

python - 将预定义数组插入大数组并迭代移动较小数组的位置

c++ - 在 C++ 中使用 STL 时解决边界错误

php - 这个 MySQL 查询有问题吗?

java - JPA persit 以多对一关系创建新的现有实体

python - 运行源代码中包含 Unicode 字符的 Python 2.7 代码

python Pandas : Conditional rolling count

python - pandas 中添加列的一些计算

java - <> 在 Java 中做什么?