2015-05-30 65 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')