1、可以使用itertools.product在标准库中使用以获取笛卡尔积。
from itertools import product somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] result = list(product(*somelists)) print(result)
2、迭代方法。
def cartesian_iterative(pools): result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] return result
3、递归方法。
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]
4、Lambda方法。
def cartesian_reduct(pools): return reduce(lambda x,y: product(x,y) , pools)
以上就是Python从列表中获取笛卡尔积的方法,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。