在 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


青春有我
浏览 157回答 2
2回答

牧羊人nacy

你不需要这么多循环。只需使用combinations并product从itertoools>>> from itertools import combinations, product>>>&nbsp;>>> v1 = [1, 2]>>> v2 = ["a","b"]>>>&nbsp;>>> 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)]>>>&nbsp;>>> for i, (x,y) in enumerate(product(all_v2, all_v1)):...&nbsp; &nbsp; &nbsp;print (f'com{i} <-{x} with {y}')...&nbsp;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)

杨魅力

来自 itertools 的结果product()是两个列表的笛卡尔积。通过使用此函数,您可以避免所有循环:import itertoolsv1 = [1, 2]v2 = ["a","b"]combinations = list(itertools.product(v1, v2))>> [(1, "a"), (1, "b"), (2, "a"), (2, "b")]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python