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

查看:37
本文介绍了在 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]Class2 = [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 中做到这一点.我确定有,但我不确定最有效的方法是什么.也许是一个for in"循环语句,它遍历每个类的每个元素?或者现在我正在研究这个,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天全站免登陆