“如何不均匀地迭代两个列表”

我无法为我遇到的这个非常具体的问题找到解决方案。本质上,我有两个列表,每个列表有两个元素:[A, B] 和 [1,2]。我想创建一个嵌套循环,在第二个列表上迭代和扩展,并在每次迭代后添加第一个列表的每个元素。


最后我想看到的是:


A B 

1 A

1 B

2 A

2 B

1 1 A

1 2 A

2 1 A

2 2 A

1 1 B

1 2 B

2 1 B

2 2 B

1 1 1 A

1 1 2 A

...

我的问题是,我尝试这样做递归地将 A 和 B 分开,以便出现这种模式(也请注意不同的第一行):


A

1 A

2 A

1 1 A

1 2 A

2 1 A

2 2 A

1 1 1 A

1 1 2 A

...

B

1 B

2 B

1 1 B

1 2 B

2 1 B

2 2 B

1 1 1 B

1 1 2 B

...

我如何将 A 和 B 放在一起?


这是代码:


def second_list(depth):

    if depth < 1: 

        yield ''

    else:

        for elements in [' 1 ', ' 2 ']:

            for other_elements in list (second_list(depth-1)): 

                yield elements + other_elements



for first_list in [' A ', ' B ']:

    for i in range(0,4): 

        temp=second_list(i)

        for temp_list in list(temp):

            print temp_list + first_list


动漫人物
浏览 144回答 1
1回答

慕田峪7331174

我会尝试以下风格的东西:l1 = ['A', 'B']l2 = ['1', '2']def expand(l1, l2):&nbsp; &nbsp; nl1 = []&nbsp; &nbsp; for e in l1:&nbsp; &nbsp; &nbsp; &nbsp; for f in l2:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;nl1.append(f+e)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;yield nl1[-1]&nbsp; &nbsp; yield from expand(nl1,l2)for x in expand(l1, l2):&nbsp; &nbsp; print (x)&nbsp; &nbsp; if len(x) > 5:&nbsp; &nbsp; &nbsp; &nbsp; break注意:输出的第一行似乎不是同一规则的产物,所以这里没有生成,如果需要,可以手动添加。注意2:不构建新生成元素的列表会更优雅,但是你必须计算它们两次。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python