在Python中将列表的元素插入到另一个列表的中间

2024-04-23 06:47:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一份清单:

["*****", "*****"]

我想在列表中间插入另一个列表的元素,如下所示:

["*****", "abc", "ded", "*****"]

但是,我的尝试会产生嵌套在另一个列表中的列表:

["*****", ["abc", "ded"], "*****"]

这是我的代码:

def addBorder(picture):

    length_of_element = len(picture[0])
    number_of_asterisks = length_of_element + 2
    new_list = ['*' * number_of_asterisks for i in range(0, 2)]
    new_list.insert(len(new_list)//2, [value for value in picture])
    
    return new_list

我知道我的代码很好。我只是想知道我需要做些什么调整


Tags: of代码innumber列表newforlen
1条回答
网友
1楼 · 发布于 2024-04-23 06:47:31
a = ['****', '****']
b = ['abc', 'efg']
mid_index = len(a)//2 # Integer result for a division

result = a[:mid_index] + b + a[mid_index:]

如果要将结果直接分配给a,还可以简单地执行以下操作:

a[mid_index:mid_index] = b

相关问题 更多 >