簡體   English   中英

如何找到列表中缺少的元素?

[英]How to find missing elements in a list?

我有一個目標清單

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

和一個輸出列表為

output_list = ['two','three','four', 'five']

target_list是固定的,而output_list將根據某些函數的輸出而改變。 我想根據output_list的觀察結果找到target_list會丟失的元素。

如上例所示,元素one缺失。 我也想計算缺失元素的數量。 你能幫我用python做嗎?

您可以使用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})
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

您將不得不比較列表中的每個項目是否包含在另一個項目中; 可能最有效的方法是使用sets()並提取它們的差異。

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

print(set(target_list).difference(set(output_list)))

輸出:

set(['one'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM