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

51
在JavaScript中,我可以使用splice将多个元素的数组插入到数组中:myArray.splice(insertIndex, removeNElements, ...insertThese)
但是在Python中,似乎没有一种不需要连接列表的类似方法。是否有这样的方法?(已经有一个关于 插入单个项目而不是多个项目的问答。)
例如myList = [1, 2, 3],我想通过调用myList.someMethod(1, otherList)来插入otherList = [4, 5, 6],以获得[1, 4, 5, 6, 2, 3]

你在寻找 list.extend 吗? - mgilson
1
@mgilson 不是的, extend 只会在末尾添加,对吧? 我想要能够根据 insertIndex 指示在列表中的任何位置插入它。 - TheRealFakeNews
1
@alfasin 不是的,因为那使用了连接。而且那个帖子的 OP 正在寻求排列。 - TheRealFakeNews
@AlanH,问题中的示例正是另一个问题描述如何完成的:mylist[0:1] + otherlist + mylist[2:] - Nir Alfasi
4
不同意复制。另一个问题想要将一个给定的项插入到多个不相关的位置中。 https://dev59.com/o3E95IYBdhLWcg3wp_kg - Ciro Santilli OurBigBook.com
7个回答

112
要扩展一个列表,只需使用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]

5
这个可以完成任务,但并没有直接回答实际问题。答案应该是类似于 myList[1:1] = otherList 这样的东西。 - Manngo
@Manngo 这个确实完全符合要求,应该被接受为答案。(虽然我不知道在性能方面是否都一样) - OverLordGoldDragon

5

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

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

5
注意,这将返回一个新列表,不像插入方法。 - Quantum7

1

我不确定这个问题是否仍在关注,但我最近编写了一段类似于此处所需的简短代码。我正在编写一个交互式脚本来执行一些分析,因此我有一系列输入用于读取CSV中的某些列:

X = input('X COLUMN NAME?:\n')
Y = input('Y COLUMN NAME?:\n')
Z = input('Z COLUMN NAME?:\n')
cols = [X,Y,Z]

然后,我将for循环压缩为一行,以便读取到所需的索引位置:
[cols.insert(len(cols),x) for x in input('ENTER COLUMN NAMES (COMMA SEPARATED):\n').split(', ')]

这可能不是非常简洁(我很想知道什么更好的方法!),但这可以清理一些代码。


0
以下代码可以实现此功能,同时避免创建新列表。不过我仍然更喜欢 @RFV5s 的方法。
def insert_to_list(original_list, new_list, index):
    
    tmp_list = []
    
    # Remove everything following the insertion point
    while len(original_list) > index:
        tmp_list.append(original_list.pop())
    
    # Insert the new values
    original_list.extend(new_list)
    
    # Reattach the removed values
    original_list.extend(tmp_list[::-1])
    
    return original_list

请注意,需要反转tmp_list的顺序,因为pop()从末尾开始放弃original_list中的值。

1
为什么要逐个弹出项目并将它们添加到另一个列表中? - Alexander

0

Python的JavaScript等效语言

myArray.splice(insertIndex, removeNElements, ...insertThese) 

会是:

my_list[insert_index:insert_index + remove_n_elements] = insert_these

0
Modifying the solution shared by RFV in earlier post.
Solution:
list1=list1[:position] + list2 + list1[position:]
    
Ex: Trying to insert the list of items at the 3rd index(2 is used in code snippet as positive indexing starts from 0 in Python)

list1=[0,1,23,345.22,True,"Data"] 
print(type(list1))
print(list1)
list2=[2,3,4,5]
list1=list1[:2] + list2 + list1[2:]
print("After insertion the values are",list1)
    
Ouput for the above code snippet.
<class 'list'>
[0, 1, 23, 345.22, True, 'Data']
After insertion the values are [0, 1, 2, 3, 4, 5, 23, 345.22, True, 'Data']

1
目前你的回答不够清晰,请[编辑]以添加更多细节,帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

-1
使用 listname.extend([val1,val2,val,etc])。

感谢您提供答案。您是否可以编辑您的答案并包含代码解释?这将有助于未来的读者更好地理解正在发生的事情,特别是那些对该语言感到陌生并且难以理解概念的社区成员。 - STA
与Corvus的答案相同的解决方案。 - Eric Aya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接