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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39541370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:25:55  来源:igfitidea点击:

How to insert multiple elements into a list?

pythonlistinsert

提问by AlanH

In JavaScript, I can use spliceto insert an array of multiple elements in to an array: myArray.splice(insertIndex, removeNElements, ...insertThese)

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

But I can't seem to find a way to do something similar in Python withouthaving concat lists. Is there such a way?

但是我似乎无法找到一种方法在没有concat 列表的情况下在 Python 中做类似的事情。有这样的方法吗?

For example myList = [1, 2, 3]and I want to insert otherList = [4, 5, 6]by calling myList.someMethod(1, otherList)to get [1, 4, 5, 6, 2, 3]

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

回答by mgilson

To extend a list, you just use list.extend. To insert elements from any iterable at an index, you can use slice assignment...

要扩展列表,您只需使用list.extend. 要在索引处插入来自任何可迭代对象的元素,您可以使用切片赋值...

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

回答by RFV5s

Python lists do not have such a method. Here is helper function that takes two lists and places the second list into the first list at the specified position:

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

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