2015-05-30 66 views
-1

我怎么能拒绝这样的:获得共同的元组元素

(("and", "dog"), ("a", "dog")) 

进入这个:

("and", "dog", "a") 

这意味着越来越常见的元素"dog"只有一次。

+0

是订货重要?如果没有,只需使用['set'](https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset)。 – jonrsharpe

回答

3
>>> tuple(set(("and", "dog")) | set(("a", "dog"))) 
('and', 'a', 'dog') 

或者一般:

import operator 
tuple(reduce(operator.__or__, map(set, mytuples))) 
0

你可以将它转换为set

diff = (set(("a","dog")) - set(("and","dog"))) 
result = list(("and","dog")) + list((diff)) 
print(result) #['and', 'dog', 'a'] 
0

如果顺序并不重要:

>>> tuple(set.union(*map(set, tuples))) 
('and', 'a', 'dog') 

如果为了做事情:

>>> seen = set() 
>>> tuple(elem for tupl in tuples for elem in tupl 
      if elem not in seen and not seen.add(elem)) 
('and', 'dog', 'a')