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

epggiuax  于 2023-03-11  发布在  Python
关注(0)|答案(7)|浏览(165)

在JavaScript中,我可以使用splice将多个元素的数组插入到数组中:myArray.splice(insertIndex, removeNElements, ...insertThese) .
但是我似乎找不到一种方法在Python中 * 不 * 使用concat列表来做类似的事情,有这样的方法吗?(已经有关于inserting single items的问答,而不是多个。)
例如myList = [1, 2, 3],我想通过调用myList.someMethod(1, otherList)来获得[1, 4, 5, 6, 2, 3],从而插入otherList = [4, 5, 6]

gwbalxhn

gwbalxhn1#

要扩展列表,只需使用list.extend;要在索引处插入任何可迭代对象中的元素,可以使用slice assignment...

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

rqmkfv5c2#

Python列表没有这样的方法,这里有一个helper函数,它接受两个列表,并把第二个列表放到第一个列表的指定位置:

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

yks3o0rb3#

我不确定这个问题是否还在继续,但我最近写了一个简短的代码,类似于这里所问的问题。我正在写一个交互式脚本来执行一些分析,所以我有一系列的输入来读取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(', ')]

这可能不一定像它可能的那样简洁(我很想知道什么可能工作得更好!),但这可能会清理一些代码。

k4emjkb1

k4emjkb14#

下面的代码在避免创建新列表的情况下实现了这一点,但是我仍然更喜欢@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的末尾向后给出这些值。

fquxozlt

fquxozlt5#

JavaScript的Python等价物

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

将是:

my_list[insert_index:insert_index + remove_n_elements] = insert_these
nzk0hqpo

nzk0hqpo6#

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

wixjitnu7#

使用列表名。扩展([val1,val2,val,etc])

相关问题