我有一个目标列表
target_list = ['one', 'two', 'three','four', 'five']
输出列表为
output_list = ['two','three','four', 'five']
target_list
是固定的,而output_list
会根据某些功能的输出而改变。我想根据target_list
的观察结果找出output_list
中遗漏哪个元素。
如上例所示,缺少元素one
。我还想计算缺失元素的数量。你能帮我在python中做这件事吗?
答案 0 :(得分:2)
您可以使用Counter找到缺少的元素。每个缺失的元素都会出现。
from collections import Counter
target_list = ["one", "two", "three", "four", "five"]
output_list = ['two','three','four', 'five']
Counter(target_list)-Counter(output_list)
输出:
Counter({'one': 1})
答案 1 :(得分:1)
target_list=['one', 'two', 'three','four', 'five']
output_list=['two','three','four', 'five']
l = [x for x in target_list if x not in output_list]
print("Number of items missing: " + len(l))
for x in target_list:
if x in l:
print(x + " is missing")
else:
print(x + " is not missing")
输出
one is missing
two is not missing
three is not missing
four is not missing
five is not missing
答案 2 :(得分:1)
如果列表中的每个项目都包含在另一个项目中,您将不得不进行比较;可能最有效的方法是使用sets()并提取它们的差异。
set(['one'])
null