如何使用 a 以不同的顺序对具有相同元素的序列进行分组?collections.defaultdict https://docs.python.org/3.6/library/collections.html#collections.defaultdict,然后从每个键中选取第一个元素:
from itertools import product
from collections import defaultdict
l = [[1] ,[1,2,3], [1,2,3]]
d = defaultdict(list)
for x in product(*l):
d[tuple(sorted(x))].append(x)
print([x[0] for x in d.values()])
这使:
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3)]
或者,也可以通过保留一组已添加的内容来完成此操作:
from itertools import product
l = [[1] ,[1,2,3], [1,2,3]]
seen = set()
combs = []
for x in product(*l):
curr = tuple(sorted(x))
if curr not in seen:
combs.append(x)
seen.add(curr)
print(combs)
# [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3)]
如果您不想排序,请考虑使用frozenset https://docs.python.org/3/library/stdtypes.html?highlight=frozenset#frozenset with collections.Counter() https://docs.python.org/3.6/library/collections.html#collections.Counter:
from collections import Counter
from itertools import product
l = [[1] ,[1,2,3], [1,2,3]]
seen = set()
combs = []
for x in product(*l):
curr = frozenset(Counter(x).items())
if curr not in seen:
seen.add(curr)
combs.append(x)
print(combs)
# [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3)]
Note:您还可以使用setdefault()
对于第一种方法,如果您不想使用defaultdict()
.