添加唯一的无序集列表

时间:2012-07-01 19:36:49

标签: python algorithm

我必须从数字列表中创建唯一的,无序的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)]
  6. python中最优化的解决方案是什么?

4 个答案:

答案 0 :(得分: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)]

答案 1 :(得分: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)

答案 2 :(得分:1)

改为使用frozenset,并将其添加到set

答案 3 :(得分:1)

扩展Ignacio关于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])])