简体   繁体   中英

“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]. 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
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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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