简体   繁体   English

如何在 2 个列表中找到共同的值并打印所有不常见的值?

[英]How to find values in common in 2 lists and print all uncommon values?

I attempted using an if statement to see if the values are the same but I'm not sure what is next?我尝试使用 if 语句来查看值是否相同,但我不确定下一步是什么?

a = [1, 2, 4, 5, 6, 7, 4, 5, 6, 7, 5, 6, 7]
b = [2, 4, 5, 6, 7, 8, 5, 4, 6, 8, 5, 6, 7, 4, 3, 5]

Try this: List comprehensions试试这个:列表推导

# for each element (i) in each list only those not 
# present in the other list will be in the new list

a_uncommon = [i for i in a if i not in b]
b_uncommon = [i for i in b if i not in a]

print('these are the uncommon elements in a', a_uncommon)
print('these are the uncommon elements in b', b_uncommon)

you could also use set , you can refer to the operation in sets in the following link https://docs.python.org/2/library/sets.html :您也可以使用set ,您可以参考以下链接https://docs.python.org/2/library/sets.html中的集合操作:

list(set(a) & set(b))
# [2, 4, 5, 6, 7]

Edit In the case you also need the differnce:编辑如果您还需要不同之处:

a = [1, 2, 4, 5, 6, 7, 4, 5, 6, 7, 5, 6, 7]
b = [2, 4, 5, 6, 7, 8, 5, 4, 6, 8, 5, 6, 7, 4, 3, 5]

c = list(set(a) & set(b))

diff_a = list(set(a) ^ set(c))
diff_b = list(set(b) ^ set(c))
print(c) # [2, 4, 5, 6, 7]
print(diff_a) # [1]
print(diff_b) # [3, 8]

To find the common you should use the intesection , & , of 2 sets.要找到共同点,您应该使用 2 个集合的intesection&

To find the uncommon you should use the difference , ^ , of 2 sets.要找到不常见的,您应该使用 2 组的差异^

To find items in either list but not both, you want to get the symmetric difference要在任一列表中查找项目但不能同时在两个列表中查找项目,您需要获得对称差异

a = [1, 2, 4, 5, 6, 7, 4, 5, 6, 7, 5, 6, 7]
b = [2, 4, 5, 6, 7, 8, 5, 4, 6, 8, 5, 6, 7, 4, 3, 5]

list(set(a) ^ set(b))
# [1, 3, 8]
# alternatively: set(a).symmetric_difference(b)

This will be more efficient than nested loops.这将比嵌套循环更有效。

If you want the items in one that are not in the other, a simple difference will work:如果您想要一个不在另一个的项目,一个简单的区别将起作用:

set(a) - set(b)
# {1}

set(b) - set(a)
# {3, 8}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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