2 回答
TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊
你不需要這么多循環(huán)。只需使用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)
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
來自 itertools 的結(jié)果product()是兩個(gè)列表的笛卡爾積。通過使用此函數(shù),您可以避免所有循環(huán):
import itertools
v1 = [1, 2]
v2 = ["a","b"]
combinations = list(itertools.product(v1, v2))
>> [(1, "a"), (1, "b"), (2, "a"), (2, "b")]
添加回答
舉報(bào)
