2 回答
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)
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")]
添加回答
举报