我必须从数字列表中创建唯一的、无序的 2 个元素集。然后将每个集合插入到一个列表中。
例如:
- 集合列表 = [(2,1)]
- 唯一编号 = [1,2,3]
- 独特的集合 - (1,2),(2,3),(1,3)
setslist
如果它不存在,则插入每个集合。(集合是无序的。所以 (1,2) 与 (2,1) 相同)- 最后
setslist = [(2,1),(2,3),(1,3)]
python中最优化的解决方案是什么?
>>> 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)]
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)
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])])
使用frozenset
s 代替,并将它们添加到set
.