【问题标题】:Find all possible combinations of items in array of arrays在数组数组中查找所有可能的项目组合
【发布时间】:2019-02-21 10:09:30
【问题描述】:

我有一个数组,看起来像这样:

arrays = [['a', 'b'], [1, 2], ['x', 'y', 'z']]

但也可以扩展。

我需要以所有可能的组合(a 1 xa 2 xa 1 ya 1 z、ecc)将这些提供给my_function(a_or_b, one_or_two, x_y_or_x)。使用 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 或 itertools 中其他非常有用的工具之一

标签: python arrays


【解决方案1】:

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')

【讨论】:

    猜你喜欢
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多