gpt4 book ai didi

不重复的Python组合

转载 作者:太空狗 更新时间:2023-10-29 20:39:27 26 4
gpt4 key购买 nike

我有一个数字列表,我想从中进行组合。如果我有列表:

t = [2,2,2,2,4]
c = list(itertools.combinations(t, 4))

结果是:

(2, 2, 2, 2)
(2, 2, 2, 4)
(2, 2, 2, 4)
(2, 2, 2, 4)
(2, 2, 2, 4)

但我想得到:

(2, 2, 2, 2)
(2, 2, 2, 4)

除了创建新列表并遍历第一个列表之外,是否有可能消除重复项?

最佳答案

我知道这已经晚了,但我想补充一点。

set(itertools.combinations(t, 4)) 在大多数情况下会做得很好,但它仍然会在内部迭代所有重复组合,因此计算量可能很大。如果实际的唯一组合不多,情况尤其如此。

这个只迭代唯一的组合:

from itertools import chain, repeat, count, islice
from collections import Counter


def repeat_chain(values, counts):
return chain.from_iterable(map(repeat, values, counts))


def unique_combinations_from_value_counts(values, counts, r):
n = len(counts)
indices = list(islice(repeat_chain(count(), counts), r))
if len(indices) < r:
return
while True:
yield tuple(values[i] for i in indices)
for i, j in zip(reversed(range(r)), repeat_chain(reversed(range(n)), reversed(counts))):
if indices[i] != j:
break
else:
return
j = indices[i] + 1
for i, j in zip(range(i, r), repeat_chain(count(j), counts[j:])):
indices[i] = j


def unique_combinations(iterable, r):
values, counts = zip(*Counter(iterable).items())
return unique_combinations_from_value_counts(values, counts, r)

用法:

>>> list(unique_combinations([2, 2, 2, 2, 4], 4)) # elements must be hashable
[(2, 2, 2, 2), (2, 2, 2, 4)]

# You can pass values and counts separately. For this usage, values don't need to be hashable
# Say you have ['a','b','b','c','c','c'], then since there is 1 of 'a', 2 of 'b', and 3 of 'c', you can do as follows:
>>> list(unique_combinations_from_value_counts(['a', 'b', 'c'], [1, 2, 3], 3))
[('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'c'), ('b', 'b', 'c'), ('b', 'c', 'c'), ('c', 'c', 'c')]

# unique_combinations() is a generator (and thus an iterator)
# so you can iterate it
>>> for comb in unique_combinations([2, 2, 2, 2, 4], 4):
... print(sum(comb))
...
8 # 2+2+2+2
10 # 2+2+2+4

请注意,itertools.combinations() 是用 C 语言实现的,这意味着在大多数情况下它比我的 python 脚本快得多。仅当重复组合比唯一组合多得多时,此代码比 set(itertools.combinations()) 方法效果更好。

关于不重复的Python组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36429507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com