[英]add unique unordered sets to list
我必须从数字列表中创建2个元素的唯一,无序集合。 然后将每个集合插入列表。
例如:
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)
请改用frozenset
,然后将它们添加到set
。
要扩展Ignacio关于frozenset
的建议,请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])])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.