2016-04-07 70 views
0

我正在研究一個程序,在該程序中我需要檢查集合中的每個元素(從集合列表中)並將其與「主集合」集合進行比較,然後將該集合附加到列表中,如果至少有一個元素兩套相匹配。比較集合元素(Python)的麻煩?

我試圖攻擊這個問題就像一個列表只是爲了實現索引不起作用。

防爆的什麼,我試圖完成:

newlist = [] 
i = set([5, 3, 1]) # <-- 'Master' Set 
z = set([5, 0, 4]) 

#Output should be -> newlist = [set([5,0,4])] 
+0

爲了將來的參考,'set'文檔是[here](https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset)。 (不幸的是,它不會出現在Google上。) – user2357112

回答

1

假設z像你的問題的說明,但不是在你的連接段列表。

newlist = [x for x in z if not i.isdisjoint(set(x))] 
# or newlist = [x for x in z if i.intersection(set(x))] 

Live demo

+0

'not x.isdisjoint(i)'可以避免創建交集。 – user2357112

+0

@ user2357112謝謝! – timrau

+0

Hm ...返回AttributeError:'list'對象沒有屬性'intersection' –

0

可以使用交集的組合和設置來解決這個問題:所以基本上

>>> s1 = set([1,2,3]) 
>>> s2 = set([3,4,5]) 
>>> s3 = set([6,7,8]) 
>>> len(s1.intersection(s2)) 
1 
>>> len(s1.intersection(s3)) 
0 

,寫一個if語句來檢查兩路口的長集。如果長度大於0,則使新列表等於第二組。