gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:11:54 32 4
gpt4 key购买 nike

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

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com