简体   繁体   English

在python上重复的所有可能的组合和排列

[英]All the possible combination and permutations with repetition on python

Essentially, I want to do基本上,我想做

def get_all_possible(N)
    for i0 in range(N) :
        for i1 in range(N) :
            for i2 in range(N) :
             ... for iNm1 in range(N) : #Nm1 is N minus 1
                     yield [i0,i1,i2,i3,...,iNm1]

and make a list of all the possible combination of number 0-N at each index and their permutations.并列出每个索引处数字0-N的所有可能组合及其排列。 So when N=4 then there should be 4^4 possible combinations to be output.因此,当N=4 ,应该输出4^4可能的组合。 This nested for loop is not efficient, and the code is not easily expandable to general N case.这种嵌套的 for 循环效率不高,代码也不容易扩展到一般的N情况。

A solution that helps readability is itertools.product一个有助于提高可读性的解决方案是itertools.product

import itertools
all_combs = list(itertools.product(range(4), repeat=4))

尝试itertools.permutationsitertools.combinations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM