Python怎么從列表中獲取笛卡爾積

這篇文章給大家分享的是有關(guān)Python怎么從列表中獲取笛卡爾積的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

創(chuàng)新互聯(lián)是一家專注于成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)達(dá)州托管服務(wù)器的網(wǎng)絡(luò)公司,有著豐富的建站經(jīng)驗(yàn)和案例。

1、可以使用itertools.product在標(biāo)準(zhǔn)庫中使用以獲取笛卡爾積。

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)

感謝各位的閱讀!關(guān)于“Python怎么從列表中獲取笛卡爾積”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

新聞標(biāo)題:Python怎么從列表中獲取笛卡爾積
文章位置:http://muchs.cn/article48/ijojhp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站收錄、建站公司、響應(yīng)式網(wǎng)站App開發(fā)、微信小程序、網(wǎng)站改版

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司

網(wǎng)站設(shè)計(jì)公司知識