新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:Python如何從列表中獲取笛卡爾積
1、可以使用itertools.product在標(biāo)準(zhǔn)庫(kù)中使用以獲取笛卡爾積。

創(chuàng)新互聯(lián)建站主營(yíng)貴德網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,成都APP應(yīng)用開發(fā),貴德h5微信小程序開發(fā)搭建,貴德網(wǎng)站營(yíng)銷推廣歡迎貴德等地區(qū)企業(yè)咨詢
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從列表中獲取笛卡爾積的方法,希望對(duì)大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
網(wǎng)站標(biāo)題:創(chuàng)新互聯(lián)Python教程:Python如何從列表中獲取笛卡爾積
分享路徑:http://m.fisionsoft.com.cn/article/cohshoe.html


咨詢
建站咨詢
