获取一系列列表的笛卡尔积?

本文翻译自:Get the cartesian product of a series of lists?

How can I get the Cartesian product (every possible combination of values) from a group of lists? 如何从一组列表中获得笛卡尔积(值的所有可能组合)?

Input: 输入:

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]

Desired output: 所需的输出:

[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...]

#1楼

参考:https://stackoom.com/question/2eTn/获取一系列列表的笛卡尔积


#2楼

Here is a recursive generator, which doesn't store any temporary lists 这是一个递归生成器,它不存储任何临时列表

def product(ar_list):
    if not ar_list:
        yield ()
    else:
        for a in ar_list[0]:
            for prod in product(ar_list[1:]):
                yield (a,)+prod

print list(product([[1,2],[3,4],[5,6]]))

Output: 输出:

[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]

#3楼

Just to add a bit to what has already been said: if you use sympy, you can use symbols rather than strings which makes them mathematically useful. 只是在已经说过的内容上加上一点:如果使用sympy,则可以使用符号而不是字符串,这使它们在数学上有用。

import itertools
import sympy

x, y = sympy.symbols('x y')

somelist = [[x,y], [1,2,3], [4,5]]
somelist2 = [[1,2], [1,2,3], [4,5]]

for element in itertools.product(*somelist):
  print element

About sympy . 关于sympy


#4楼

I would use list comprehension : 我将使用列表理解:

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]

cart_prod = [(a,b,c) for a in somelists[0] for b in somelists[1] for c in somelists[2]]

#5楼

A minor modification to the above recursive generator solution in variadic flavor: 对上述具有可变参数风格的递归生成器解决方案进行了较小的修改:

def product_args(*args):
    if args:
        for a in args[0]:
            for prod in product_args(*args[1:]) if args[1:] else ((),):
                yield (a,) + prod

And of course a wrapper which makes it work exactly the same as that solution: 当然,包装程序也可以使其与该解决方案完全相同:

def product2(ar_list):
    """
    >>> list(product(()))
    [()]
    >>> list(product2(()))
    []
    """
    return product_args(*ar_list)

with one trade-off : it checks if recursion should break upon each outer loop, and one gain : no yield upon empty call, eg product(()) , which I suppose would be semantically more correct (see the doctest). 权衡取舍 :它检查递归是否应该在每个外部循环上中断,并且要获得一个收益 :在空调用(例如product(())时没有收益,我想这在语义上会更正确(请参阅doctest)。

Regarding list comprehension: the mathematical definition applies to an arbitrary number of arguments, while list comprehension could only deal with a known number of them. 关于列表理解:数学定义适用于任意数量的参数,而列表理解只能处理已知数量的参数。


#6楼

Although there are many answers already, I would like to share some of my thoughts: 尽管已经有很多答案,但我还是想分享一些想法:

Iterative approach 迭代法

def cartesian_iterative(pools):
  result = [[]]
  for pool in pools:
    result = [x+[y] for x in result for y in pool]
  return result

Recursive Approach 递归方法

def cartesian_recursive(pools):
  if len(pools) > 2:
    pools[0] = product(pools[0], pools[1])
    del pools[1]
    return cartesian_recursive(pools)
  else:
    pools[0] = product(pools[0], pools[1])
    del pools[1]
    return pools
def product(x, y):
  return [xx + [yy] if isinstance(xx, list) else [xx] + [yy] for xx in x for yy in y]

Lambda Approach Lambda方法

def cartesian_reduct(pools):
  return reduce(lambda x,y: product(x,y) , pools)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值