0

我必须从数字列表中创建唯一的、无序的 2 个元素集。然后将每个集合插入到一个列表中。

例如:

  1. 集合列表 = [(2,1)]
  2. 唯一编号 = [1,2,3]
  3. 独特的集合 - (1,2),(2,3),(1,3)
  4. setslist如果它不存在,则插入每个集合。(集合是无序的。所以 (1,2) 与 (2,1) 相同)
  5. 最后setslist = [(2,1),(2,3),(1,3)]

python中最优化的解决方案是什么?

4

4 回答 4

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)]
于 2012-07-01T19:43:27.490 回答
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)
于 2012-07-01T19:42:13.440 回答
1

To expand on Ignacio's advice about 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])])
于 2012-07-01T21:12:52.100 回答
1

使用frozensets 代替,并将它们添加到set.

于 2012-07-01T19:39:40.500 回答