有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']]
答案 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)