简体   繁体   English

从2个列表中收集唯一值

[英]Gather unique values from 2 lists

I currently have 2 "set" lists, both contain mostly the same values ie: 我目前有2个“设置”列表,它们都包含大部分相同的值,即:

a = [1,2,3,4,5,6]

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

What I'm trying to do is compare the two and only return 7 & 8 into another list however I'm having no luck, I've tried a few methods I've found on here such as: 我想做的是比较两者,只将7和8返回到另一个列表中,但是我没有运气,我尝试了一些在这里找到的方法,例如:

c = [item for item in a if item not in b]

However I've had no luck does anyone know a quick and fairly easy method of doing this? 但是我没有运气,有人知道这样做的快速而简单的方法吗? Both lists have been "set" previously to remove any duplicates within their own lists also (just felt I should add that if that makes a difference) 之前都“设置”了两个列表,以删除其自身列表中的所有重复项(只是觉得如果有区别,我应该补充一点)

Just to be clear, as I think I wasn't sorry, the example values are already in set format, in my head for some reason when you used set on a list it acted like the array_unique PHP function. 明确地说,我想我并不后悔,示例值已经是set格式的,出于某种原因,当您在列表上使用set时,其作用类似于array_unique PHP函数。

Thanks. 谢谢。

You can use sets: 您可以使用集:

set(b) - set(a)
Out[65]: {7, 8}

Or more explicitly: 或更明确地:

set(b).difference(a)
Out[67]: {7, 8}

For symmetric difference, you can use ^ . 对于对称差异,可以使用^ It will return elements that are in a or b, but not in both. 它将返回位于a或b中的元素,但不会同时位于两个元素中。 Assume a has an additional element, 9: 假设a具有附加的元件,9:

a = [1, 2, 3, 4, 5, 6, 9]
b = [1, 2, 3, 4, 5, 6, 7, 8]
set(b) ^ set(a)
Out[70]: {7, 8, 9}

Or, 要么,

set(b).symmetric_difference(a)
Out[71]: {7, 8, 9}

If they are already sets, you can just do b - a or b ^ a . 如果已经设置,则可以执行b - ab ^ a

Your attempt does not work because there is no item in a which is not in b . 您的尝试不起作用,因为a中没有b没有的项目。 For that difference ( ba ), you need: [item for item in b if item not in a] . 对于该差异( ba ),您需要: [item for item in b if item not in a]

Another approach is using a defaultdict to count the number of occurrences of each element from both lists: 另一种方法是使用defaultdict来计算两个列表中每个元素的出现次数:

from collections import defaultdict
from itertools import chain

a = [1,2,3,4,5,6,9]

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

d = defaultdict(int)

for num in chain(a, b):
    d[num] += 1


print([key for key, value in d.items() if value == 1])

Output: 输出:

[7, 8]
list(set(a)-set(b))+list(set(b)-set(a))

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

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