我有一个数组数组,如下所示:
arrays = [['a', 'b'], [1, 2], ['x', 'y', 'z']]
但也可以扩大。
我需要将它们以所有可能的组合(my_function(a_or_b, one_or_two, x_y_or_x)
,a 1 x
,a 2 x
,a 1 y
,ecc)喂给a 1 z
。使用numpy是一种选择。
虽然它看起来像一个简单的问题,但我不知道从哪里开始......
是的,我可以循环:
for array in arrays:
for ...
然后什么?循环遍历数组意味着在我的第二次迭代中,arrays[0]
将不再是第一次,我会搞砸订单。我也有重复。
我怎样才能做到这一点?我不关心调用这些函数的顺序,但是我确实关心的是它们没有使用相同的组合调用两次,并且参数是有序的。
my_function(a, 1, x)
my_function(b, 1, x)
my_function(a, 2, x)
my_function(b, 2, x)
my_function(a, 1, y)
my_function(b, 1, y)
my_function(a, 2, y)
ecc...
itertools.product
就是这样做的。它将生成3个子列表中的所有组合。然后你可以在函数中将它们解压缩为参数:
from itertools import product
combs = product(*arrays)
for comb in combs:
my_function(*comb)
呼叫
my_function('a', 1, 'x')
my_function('a', 1, 'y')
my_function('a', 1, 'z')
my_function('a', 2, 'x')
my_function('a', 2, 'y')
my_function('a', 2, 'z')
my_function('b', 1, 'x')
my_function('b', 1, 'y')
my_function('b', 1, 'z')
my_function('b', 2, 'x')
my_function('b', 2, 'y')
my_function('b', 2, 'z')