亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Python 中打印兩個列表的組合

在 Python 中打印兩個列表的組合

青春有我 2023-03-30 17:24:57
我要打印的內容如下,為簡單起見,在每個字符串中使用 2 個變量。我認為使用循環有問題,我對 Python 有點陌生。提前致謝!com0 <-(a) with (1,)com1 <-(a) with (2,)com2 <-(a) with (1, 2)com3 <-(b) with (1,)com4 <-(b) with (2,)com5 <-(b) with (1, 2)com6 <-(a,b) with (1,)com7 <-(a,b) with (2,)com8 <-(a,b) with (1, 2)這是我試過的:import itertoolsi = 0 #v1j = 0 #v2v1 = [1, 2]v2 = ["a","b"]while j < 2**len(v2):    for K in range(0, len(v2)+1):        while i < 2**len(v1):            for L in range(0, len(v1)+1):                for subset2 in itertools.combinations(v1, L):                    for subset1 in itertools.combinations(v2, K):                        print("com{0} <-{1} with {2}".format(i,subset1,subset2))                        i+=1                        j+=1
查看完整描述

2 回答

?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

你不需要這么多循環。只需使用combinations并product從itertoools


>>> from itertools import combinations, product

>>> 

>>> v1 = [1, 2]

>>> v2 = ["a","b"]

>>> 

>>> all_v1 = [e for i in range(len(v1)) for e in combinations(v1,i+1)]

>>> all_v2 = [e for i in range(len(v1)) for e in combinations(v2,i+1)]

>>> 

>>> for i, (x,y) in enumerate(product(all_v2, all_v1)):

...     print (f'com{i} <-{x} with {y}')

... 

com0 <-('a',) with (1,)

com1 <-('a',) with (2,)

com2 <-('a',) with (1, 2)

com3 <-('b',) with (1,)

com4 <-('b',) with (2,)

com5 <-('b',) with (1, 2)

com6 <-('a', 'b') with (1,)

com7 <-('a', 'b') with (2,)

com8 <-('a', 'b') with (1, 2)


查看完整回答
反對 回復 2023-03-30
?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

來自 itertools 的結果product()是兩個列表的笛卡爾積。通過使用此函數,您可以避免所有循環:


import itertools


v1 = [1, 2]

v2 = ["a","b"]

combinations = list(itertools.product(v1, v2))

>> [(1, "a"), (1, "b"), (2, "a"), (2, "b")]


查看完整回答
反對 回復 2023-03-30
  • 2 回答
  • 0 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號