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

时间:2016-04-28 06:09:00

标签: python

有2个清单:

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 个答案:

答案 0 :(得分: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']]

这样您就可以将['meat']list_a的每个实例替换为list_b中的所有元素。这将产生您正在寻找的输出。

答案 1 :(得分:1)

切片指派。

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

List<Sudent> studentList = db.Students.Where(m=>m.name.Contains(query)).ToList();

只需使用List<Sudent> studentList = db.Students .Where(m=>m.name.Contains("d") && m.name.Contains(query)).ToList();

答案 4 :(得分: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']]

答案 5 :(得分: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)