简体   繁体   English

“如何不均匀地遍历两个列表”

[英]“How to unevenly iterate over two lists”

I cannot find a solution for this very specific problem I have. 对于这个非常具体的问题,我找不到解决方案。 In essence, I have two lists with two elements each: [A, B] and [1,2]. 本质上,我有两个包含两个元素的列表:[A,B]和[1,2]。 I want to create a nested loop that iterates and expands on the second list and adds each element of first list after each iteration. 我想创建一个嵌套循环,该循环在第二个列表上进行迭代和扩展,并在每次迭代后添加第一个列表的每个元素。

What I want to see in the end is this: 我最后想看到的是:

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
...

My problem is that my attempt at doing this recursively splits the A and B apart so that this pattern emerges (note the different first line, too): 我的问题是,我这样做的尝试是将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
...

How do I keep A and B together? 如何将A和B保持在一起?

Here is the code: 这是代码:

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

I would try something in the following style: 我会尝试以下风格的东西:

l1 = ['A', 'B']
l2 = ['1', '2']

def expand(l1, l2):
    nl1 = []
    for e in l1:
        for f in l2:
             nl1.append(f+e)
             yield nl1[-1]
    yield from expand(nl1,l2)

for x in expand(l1, l2):
    print (x)
    if len(x) > 5:
        break

Note: the first line of your output does not seem to be the product of the same rule, so it is not generated here, you can add it, if you want, manually. 注意:输出的第一行似乎不是同一规则的乘积,因此此处未生成该行,您可以根据需要手动添加它。

Note2: it would be more elegant not to build the list of the newly generated elements, but then you would have to calculate them twice. 注意2:不构建新生成的元素的列表会更优雅,但随后您必须对其进行两次计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM