如何用另一个列表中的多个元素替换列表中的一个元素?

3

有两个列表:

list_a = [['apple', 'banana', 'strawberry'], ['meat'], ['milk'], ['meat']]
list_b = [['chicken'], ['pork'], ['beef']]

如何将list_b插入到list_a中,而不是像这样插入“meat”:
list_c = [['apple', 'banana', 'strawberry'], ['chicken'], ['pork'],
['beef'], ['milk'], ['chicken'], ['pork'], ['beef']]
6个回答

3
使用for循环和.extend()列表方法:
for food in list_a:
    if food == ['meat']:
        list_c.extend(list_b)
    else:
        list_c.append(food)

print (list_c)

list_c 将会输出:

[['apple', 'banana', 'strawberry'], ['chicken'], ['pork'], ['beef'], ['milk'], ['chicken'], ['pork'], ['beef']]

你可以使用以下方法将list_a中所有的['meat']替换为list_b中的所有元素。这样就可以得到你想要的输出结果。


1

切片赋值。

>>> list_c = list_a[:]
>>> list_c[-1:] = list_b[:]
>>> list_c
[['apple', 'banana', 'strawberry'], ['chicken'], ['pork'], ['beef']]

1
>>> idx = list_a.index(['meat'])
>>> list_c = list_a[:idx] + list_b + list_a[idx + 1:]
[['apple', 'banana', 'strawberry'], ['chicken'], ['pork'], ['beef'], ['milk']]

1
def replace(index, L1, L2):
    return L1[0:index] + L2 + L1[index+1:]

只需使用 slice

1

针对您最后的更改..:

list_a = [['apple', 'banana', 'strawberry'], ['meat'], ['milk'], ['meat']]
list_b = [['chicken'], ['pork'], ['beef']] 
list_c = []
for x in list_a:
    if x == ["meat"]:
        for y in list_b:
            list_c.append(y)
    else:
        list_c.append(x)

list_c
[['apple', 'banana', 'strawberry'], ['chicken'], ['pork'], ['beef'], ['milk'], ['chicken'], ['pork'], ['beef']]

0
list_a = [['apple', 'banana', 'strawberry'], ['meat'], ['milk']]
list_b = [['chicken'], ['pork'], ['beef']]

deletitem = ['meat']

def newlist(deletetemlist,list_a,list_b):
    deletitemidx = list_a.index(deletetemlist)
    print(list_a[:deletitemidx] + list_b + list_a[deletitemidx + 1:])

newlist(deletitem,list_a,list_b)

@AKS,谢谢并修改了它。 - backtrack

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