【问题标题】:How to apply itertools.product to elements of a list of lists?如何将 itertools.product 应用于列表列表的元素?
【发布时间】:2011-03-03 07:37:59
【问题描述】:

我有一个数组列表,我想获得数组中元素的笛卡尔积。

我会用一个例子来使这个更具体...

itertools.product 似乎可以解决问题,但我被困在一个小细节上。

arrays = [(-1,+1), (-2,+2), (-3,+3)];

如果我这样做

cp = list(itertools.product(arrays));

我明白了

cp = cp0 = [((-1, 1),), ((-2, 2),), ((-3, 3),)]

但我想得到的是

cp1 = [(-1,-2,-3), (-1,-2,+3), (-1,+2,-3), (-1,+2,+3), ..., (+1,+2,-3), (+1,+2,+3)].

我尝试了一些不同的方法:

cp = list(itertools.product(itertools.islice(arrays, len(arrays))));
cp = list(itertools.product(iter(arrays, len(arrays))));

他们都给了我cp0而不是cp1

有什么想法吗?

提前致谢。

【问题讨论】:

标签: python itertools cartesian-product


【解决方案1】:
>>> list(itertools.product(*arrays))
[(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)]

这会将所有对作为单独的参数提供给product,然后它将为您提供它们的笛卡尔积。

您的版本不起作用的原因是您只给了product 一个参数。请求一个列表的笛卡尔积是一种简单的情况,并返回一个仅包含一个元素的列表(作为参数给出的列表)。

【讨论】:

    【解决方案2】:
    >>> arrays = [(-1,+1), (-2,+2), (-3,+3)]
    >>> list(itertools.product(*arrays))
    [(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)]
    

    【讨论】:

    【解决方案3】:

    您可以使用 itertools.product 在三个 rurch 中完成此操作

    lst=[]
    arrays = [(-1,+1), (-2,+2), (-3,+3)]  
    
    import itertools 
    
    for i in itertools.product(*arrays):
             lst.append(i)
    
    
    
    print(lst)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-20
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      相关资源
      最近更新 更多