当前位置: 首页 > 图灵资讯 > 行业资讯> Python如何从列表中获取笛卡尔积

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

发布时间:2024-06-28 21:38:22

1、itertols可以使用.在标准库中使用product获取笛卡尔积。

fromitertoolsimportproduct

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

result=list(product(*somelists))
print(result)

2、迭代方法。

defcartesian_iterative(pools):
result=[[]]
forpoolinpools:
result=[x+[y]forxinresultforyinpool]
returnresult

3、递归方法。

defcartesian_recursive(pools):
iflen(pools)>2:
pools[0]=product(pools[0],pools[1])
delpools[1]
returncartesian_recursive(pools)
else:
pools[0]=product(pools[0],pools[1])
delpools[1]
returnpools
defproduct(x,y):
return[xx+[yy]ifisinstance(xx,list)else[xx]+[yy]forxxinxforyyiny]

4、Lambda方法。

defcartesian_reduct(pools):
returnreduce(lambdax,y:product(x,y),pools)

以上是Python从列表中获取笛卡尔积的方法,希望对大家有所帮助。更多多Python学习指导:python基础教程

本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。

相关文章

python3兼容python2吗

python3兼容python2吗

2025-05-09
python3 whl怎么安装

python3 whl怎么安装

2025-05-09
python 字典怎么提取value

python 字典怎么提取value

2025-05-09
python 怎样计算字符串的长度

python 怎样计算字符串的长度

2025-05-09
python 怎么样反向输出字符串

python 怎么样反向输出字符串

2025-05-09
python 怎么判断字符串开头

python 怎么判断字符串开头

2025-05-09