在Python的组合生成 [英] Generating Combinations in python

查看:147
本文介绍了在Python的组合生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何去这在Python,如果甚至有可能。我需要做的就是创建3个独立的数组的数组(或矩阵,或矢量?)。每个阵列为4元素,例如,它们返回这样:

I am not sure how to go about this in Python, if its even possible. What I need to do is create an array (or a matrix, or vector?) from 3 separate arrays. Each array as 4 elements as such, they return this:

的Class1 = [1,2,3,4]
等级2 = [1,2,3,4]
在Class3 = [1,2,3,4]

Class1 = [1,2,3,4] Class2 = [1,2,3,4] Class3 = [1,2,3,4]

现在我想做的是回到这三个类的所有可能的组合是什么。

Now what I would like to do is return all possible combinations of these three classes.

例如:

1 1 1结果
 2 1 1结果
 3 1 1结果
 4 1 1结果
 1 2 1搜索
 2 2 1结果
 3 2 1结果
 4 2 1 ...

1 1 1
2 1 1
3 1 1
4 1 1
1 2 1
2 2 1
3 2 1
4 2 1...

...等,以64行(4元素*为每个类16种可能的组合= 64行

...and so on to 64 rows (4 elements *16 possible combinations for each class = 64 rows

我希望有一种方法在Python做到这一点。我肯定是有的,但我不知道最有效的方式去将是什么。也许为循环语句在每一类中的每个元素进行迭代?还是现在,我研究这个,就和itertools处理呢?

I am hoping there is a way to do this in python. I am sure there is but I am not sure what the most efficient way to go about would be. Perhaps a "for in" loop statement that iterates over each element for each class? Or now that I am researching this, would itertools handle this?

在此先感谢提供任何帮助。

Thanks in advance for any help offered.

推荐答案

你想要什么叫做笛卡尔产品

import itertools

iterables = [ [1,2,3,4], [88,99], ['a','b'] ]

for t in itertools.product(*iterables):
    print t

这篇关于在Python的组合生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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