不重复的Python组合

标签 python

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

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/

相关文章:

python - 使用从 Cython 中的方法创建的 PyCapsule 结果错误

postgresql - 如何用 Python 编写这段代码?

python - 如何确定嵌套列表中的所有元素是否唯一?

Python - 这两行是做什么的?

python - Python scikit-learn 每次运行后聚类结果的变化

python - 使用python减少for循环中的行数

python - 如何在 python 中从 tableau server 中删除工作簿

python - QAction 可以用于多个任务吗?

Python SQL 炼金术 : table with no primary keys and duplicate values?

python - Django - 多站点