2012-07-01 46 views
0

我必須從數字列表中創建每個2個元素的唯一無序集。然後將每個集合插入到列表中。將唯一的無序集添加到列表

例如:

  1. setslist = [(2,1)]
  2. uniquenumbers = [1,2,3]
  3. 獨特集 - (1,2),(2,3) ,(1,3)
  4. 如果它們不存在,則在setslist中插入每個集合。 (集合是無序的。所以(1,2)是一樣的(2,1))
  5. 最終setslist = [(2,1),(2,3),(1,3)]

什麼是蟒蛇最優化的解決方案嗎?

+0

確實'setslist'必須訂購? –

+0

不可以。它也可以是(1,2) – jerrymouse

+0

我的意思是列表本身。它可以是'set'而不是'list'嗎? –

回答

2
import itertools 
existing_sets = set(frozenset(x) for x in setslist) 
new_sets = set(frozenset(x) for x in itertools.combinations(uniquenumbers, 2)) 
setslist = list(existing_sets | new_sets) 
+0

+1 @amber that worked :) – jerrymouse

1

改爲使用frozenset s,並將它們添加到set

+0

請添加一個小例子 – jerrymouse

+1

創建'frozenset'或將項目添加到'set'? –

+0

+1 Ignacio,第一次使用frozenset,他們很棒.. – jerrymouse

5
>>> from itertools import combinations 
>>> lis=[1,2,3,4,5] 
>>> [x for x in combinations(lis,2)] 
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)] 
+0

+1 @ Ashwini謝謝:) – jerrymouse

1

要在伊格納西奧的約frozenset建議擴大:

In [1]: from itertools import combinations 

In [2]: sets = set([frozenset([1, 2])]) 

In [3]: uniquenumbers = [1,2,3] 

In [4]: sets.update(map(frozenset, combinations(uniquenumbers, 2))) 

In [5]: sets 
Out[5]: set([frozenset([1, 3]), frozenset([1, 2]), frozenset([2, 3])]) 
+0

+1 @Lev Thanks :) – jerrymouse