首页 > 解决方案 > 在 Python 中打印两个列表的组合

问题描述

我要打印的是以下内容,为简单起见,在每个字符串中使用 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 itertools

i = 0 #v1
j = 0 #v2

v1 = [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

标签: pythonlistcombinationsitertools

解决方案


from itertools 产生两个列表的product()笛卡尔积。通过使用此功能,您可以避免所有循环:

import itertools

v1 = [1, 2]
v2 = ["a","b"]
combinations = list(itertools.product(v1, v2))
>> [(1, "a"), (1, "b"), (2, "a"), (2, "b")]

推荐阅读