[英]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.