在Python中找到两个元组中的缺失元素

问题描述:

我有两个元组a = (('1',), ('2',), ('3',),)b = (('1',), ('3',),)。我需要得到结果为(('2',),),因为2是存在于a而不是b中的元素。在Python中找到两个元组中的缺失元素

我提到这个Find intersection of two lists?Is there a way to get the difference and intersection of tuples or lists in Python?获得一个想法,但这些是为列表而不是元组。我无法为元组使用intersection()。

有没有办法可以在python元组中获得a-b

转换为set那么你可以得到的差值,然后将其转换回tuple使用tuple()功能:

a = (('1',), ('2',), ('3',),) 
b = (('1',), ('3',),) 

result = tuple(set(a) - set(b)) 
print(result) 

运行例如:https://repl.it/M1FD/1


如果你想Symmetric Difference,在任一组元素但不在交点处:

set(a)^set(b) 

或者:

set(a).symmetric_difference(set(b)) 

运行例如:https://repl.it/M1FD/2

Sets对此非常有用。

如果你只寻找那些在a元素,但不是在b

set(a) - set(b) 

如果你正在寻找的是在元组中的任何一个元素,而不是其他:

set(a)^set(b) 

你仍然可以使用集作为在链接的答案描述:

In [1]: a = (('1',), ('2',), ('3',),) 
In [2]: b = (('1',), ('3',),) 
In [3]: set(a).intersection(set(b)) 
Out[3]: {('1',), ('3',)} 
In [4]: set(a).difference(set(b)) 
Out[4]: {('2',)}