[英]Compare between lists with different lengths?
我正在比較兩個不同的列表。 我需要獲取每個列表的唯一元素(其他列表中沒有的元素)。
每個新列表都包含另一個列表中不存在的內容。
例如:
list1 = ['apple', 'coffee', 'orange', 'sugar']
list2 = ['apple', 'grape', 'orange', 'eggplant', 'pineapple']
預期 output
new_list1 = ['coffee', 'sugar']
new_list2 = ['grape', 'eggplant', 'pineapple']
最直接的方法是使用 集合
例子:
list1 = set(['apple', 'coffee', 'orange', 'sugar'])
list2 = set(['apple', 'grape', 'orange', 'eggplant', 'pineapple'])
new_list1 = list(list1 - list2)
new_list2 = list(list2 - list1)
如果您只需要每個列表中的唯一元素而不將它們放在單獨的列表中,請使用 XOR 運算符進行集合而不是差異:
list1 = ['apple', 'coffee', 'orange', 'sugar']
list2 = ['apple', 'grape', 'orange', 'eggplant', 'pineapple']
unique = set(list1) ^ set(list2)
您可以像這樣優化上述解決方案:
>>> list(set(list1)-set(list2))
['coffee', 'sugar']
>>> list(set(list2)-set(list1))
['eggplant', 'grape', 'pineapple']
簡單的循環示例,但不一定是最有效的:
new_list_1 = [item for item in list1 if item not in list2]
new_list_2 = [item for item in list2 if item not in list1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.