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

时间:2016-09-16 23:27:12

标签: python list insert

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

但是我似乎找不到在Python 中做类似的事情而没有有concat列表的方法。有这样的方式吗?

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

4 个答案:

答案 0 :(得分:26)

要扩展列表,只需使用list.extend即可。要从索引中的任何iterable插入元素,可以使用切片赋值...

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

答案 1 :(得分:1)

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

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

答案 2 :(得分: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中的值。

答案 3 :(得分:-1)

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

相关问题