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)
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试