简体   繁体   English

比较不同长度的列表?

[英]Compare between lists with different lengths?

I am comparing two different lists.我正在比较两个不同的列表。 I need to get the unique elements of each list (those not found in the other list).我需要获取每个列表的唯一元素(其他列表中没有的元素)。

Each new list contain what didn't exist in the other.每个新列表都包含另一个列表中不存在的内容。

For example:例如:

list1 = ['apple', 'coffee', 'orange', 'sugar']
list2 = ['apple', 'grape', 'orange', 'eggplant', 'pineapple']

Expected output预期 output

new_list1 = ['coffee', 'sugar']
new_list2 = ['grape', 'eggplant', 'pineapple']

The most straightforward way is to use sets最直接的方法是使用 集合

Example:例子:

list1 = set(['apple', 'coffee', 'orange', 'sugar'])
list2 = set(['apple', 'grape', 'orange', 'eggplant', 'pineapple'])

new_list1 = list(list1 - list2)
new_list2 = list(list2 - list1)

If you just need the unique elements from each list and not have them in seperate lists use the XOR operator for sets and not difference:如果您只需要每个列表中的唯一元素而不将它们放在单独的列表中,请使用 XOR 运算符进行集合而不是差异:

list1 = ['apple', 'coffee', 'orange', 'sugar']
list2 = ['apple', 'grape', 'orange', 'eggplant', 'pineapple']

unique = set(list1) ^ set(list2)

You can optimize above solution like this:您可以像这样优化上述解决方案:

>>> list(set(list1)-set(list2))
['coffee', 'sugar']
>>> list(set(list2)-set(list1))
['eggplant', 'grape', 'pineapple']

Simple looping example but not necessarily the most efficient:简单的循环示例,但不一定是最有效的:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM