我尝试使用 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 itertoolsbinations_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计算具有重复元素的所有组合?
发布评论