如何查找列表中缺失的元素?

Jam*_*ame -1 python python-2.7

我有一个目标清单

target_list = ['one', 'two', 'three','four', 'five']
Run Code Online (Sandbox Code Playgroud)

输出列表为

output_list = ['two','three','four', 'five']
Run Code Online (Sandbox Code Playgroud)

target_list固定的,而output_list会根据某些函数的输出而变化。我想根据target_list的观察找到哪个元素会被遗漏output_list

如上例所示,one缺少该元素。我还想计算缺失元素的数量。你能帮我用 python 来做吗?

Reb*_*que 5

您必须比较列表中的每一项是否包含在另一项中;也许最有效的方法是使用sets()并提取它们的差异。

target_list = ["one", "two", "three", "four", "five"]
output_list = ['two','three','four', 'five']

print(set(target_list).difference(set(output_list)))
Run Code Online (Sandbox Code Playgroud)

输出:

set(['one'])
Run Code Online (Sandbox Code Playgroud)