ITPub博客

首页 > IT职业 > IT职场 > Python如何从列表中获取笛卡尔积

Python如何从列表中获取笛卡尔积

IT职场 作者:funnyok 时间:2021-09-11 09:47:24 0 删除 编辑

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电脑。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3137/viewspace-2828429/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2007-12-07

  • 博文量
    95
  • 访问量
    238392