如何使用itertools计算具有重复元素的所有组合? [英] How to use itertools to compute all combinations with repeating elements?

查看:67
本文介绍了如何使用itertools计算具有重复元素的所有组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 itertools 计算列表的所有组合['a', 'b', 'c']与重复元素一起使用combinations_with_replacement.问题在于,索引似乎用于区分元素:

I have tried to use itertools to compute all combinations of a list ['a', 'b', 'c'] using combinations_with_replacement with repeating elements. The problem is in the fact that the indices seem to be used to distinguish the elements:

从输入迭代返回元素的r长度子序列,允许单个元素重复多次.

Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.

组合按字典顺序排序.所以,如果输入 可迭代的被排序,组合元组将被排序 订单.

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

根据元素的位置(而不是元素的位置)将元素视为唯一 价值.因此,如果输入元素是唯一的,则生成的组合 也将是唯一的.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, the generated combinations will also be unique.

找到此代码段:

import itertools

for item in itertools.combinations_with_replacement(['a','b','c'], 3): 
    print (item)

结果如下:

('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'b')
('a', 'b', 'c')
('a', 'c', 'c')
('b', 'b', 'b')
('b', 'b', 'c')
('b', 'c', 'c')
('c', 'c', 'c')

我需要的是包含以下元素的组合集:('a', 'b', 'a')似乎丢失了.如何计算完整的组合集?

And what I need is the combination set to contain elements like: ('a', 'b', 'a') which seem to be missing. How to compute the complete combination set?

推荐答案

听起来像您想要 itertools.product :

It sounds like you want itertools.product:

>>> from itertools import product
>>> for item in product(['a', 'b', 'c'], repeat=3):
...     print item
...
('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'a')
('a', 'b', 'b')
('a', 'b', 'c')
('a', 'c', 'a')
('a', 'c', 'b')
('a', 'c', 'c')
('b', 'a', 'a')
('b', 'a', 'b')
('b', 'a', 'c')
('b', 'b', 'a')
('b', 'b', 'b')
('b', 'b', 'c')
('b', 'c', 'a')
('b', 'c', 'b')
('b', 'c', 'c')
('c', 'a', 'a')
('c', 'a', 'b')
('c', 'a', 'c')
('c', 'b', 'a')
('c', 'b', 'b')
('c', 'b', 'c')
('c', 'c', 'a')
('c', 'c', 'b')
('c', 'c', 'c')
>>>

这篇关于如何使用itertools计算具有重复元素的所有组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆