如何使用itertools计算具有重复元素的所有组合?

编程入门 行业动态 更新时间:2024-10-09 03:30:06
本文介绍了如何使用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 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计算具有重复元素的所有组合?

本文发布于:2023-11-30 12:36:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649981.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   如何使用   元素   itertools

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!