这是我尝试过的:
for i in range(len(list1)):
if str(list2[0]) == list1[i][0]:
list1.remove(str(list2[0]))
print(list1)
答案 0 :(得分:1)
您并不是在内部列表上进行操作-您的外部列表不包含字符串“ apple”。您尝试从list1
中删除“苹果”:
list1 = [["apple", "bd", "go", "d", "e"], ["bd", "e", "d", "go", "apple"], ["go", "d", "e", "bd", "apple"], ["d", "bd", "apple", "go", "e"], ["e", "apple", "go", "bd", "d"]] list2 = ["apple", "bd", "e", "d", "go"] for i in range(len(list1)): if str(list2[0]) == list1[i][0]: list1.remove(str(list2[0])) # list1 only contains lists, not strings print(list1)
# iterate over all inner lists
for inner in list1:
# and remove "apple"
inner.remove(list2[0])
print(list1)
输出:
[['bd', 'go', 'd', 'e'], ['bd', 'e', 'd', 'go'], ['go', 'd', 'e', 'bd'],
['d', 'bd', 'go', 'e'], ['e', 'go', 'bd', 'd']]
如果要创建一个新文件,请按照以下步骤操作:
no_apple = []
for inner in list1:
# filter inners with list comprehension, expluce list2[0]
no_apple.append([i for i in inner if i != list2[0]])
print(no_apple)
答案 1 :(得分:0)
创建新列表是否受到限制?
您可以为list1内的每个列表创建一个新列表,并将它们附加到新列表中
answer = []
for inside_list in list1:
new_inside_list = [value for value in inside_list if value not in list2]
answer.append(new_inside_list)
这会删除出现在list1中的list2的每个元素。
请注意,new_inside_list可能会导致列表为空。只需在附加答案之前检查它是否为空