在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)
如果你想Symmetric Difference,在任一组元素但不在交点处:
set(a)^set(b)
或者:
set(a).symmetric_difference(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',)}