Python Forum
permuting a list of lists - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: permuting a list of lists (/thread-15509.html)



permuting a list of lists - Skaperen - Jan-20-2019

suppose i have a list of lists, where each inner list begins with its name followed by a sequence of numbers. i want to have nested loops that go though the numbers of each list in every combination. if i knew how many lists there are at coding time i could simply code that many nested loops. is there any combinatorical/permutation library/module/class/function that can go through all of these?

if there are 3 lists:
# for 3 lists:
for a in listoflists[0][1:]:
    ...
    for b in listoflists[1][1:]:
        ...
        for c in listoflists[2][1:]:
            ...
            names = [n[0] for n in listoflists]
            combos = [a,b,c]
            ...
if there are 6 lists:
# for 6 lists:
for a in listoflists[0][1:]:
    ...
    for b in listoflists[1][1:]:
        ...
        for c in listoflists[2][1:]:
            ...
            for d in listoflists[3][1:]:
                ...
                for e in listoflists[4][1:]:
                    ...
                    for f in listoflists[5][1:]:
                        ...
                        names = [n[0] for n in listoflists]
                        combos = [a,b,c,d,e,f]
                        ...
i did something like this ages ago but did it in assembly language. the code was ugly even for assembly. i later tried to code it in C but when i realized that to convert my assembler logic to C i'd end up having to code with gotos in several bad places, i gave up an used the old assembly version. now, i need to do the same kind of thing, again, and i no longer even have the assembly version. i'm hoping python has already worked out this kind of thing.

i suppose i could flatten the list of lists. but the actual program needs to do things where flattening all the lists would not work. it really does need a variable amount of nesting of iterations with some of my code at every level.


RE: permuting a list of lists - ichabod801 - Jan-20-2019

It looks like you want itertools.product.


RE: permuting a list of lists - DeaD_EyE - Jan-20-2019

from random import randint
from itertools import product


products = [[randint(0, 255) for _ in range(5)] for _ in range(5)]

for prod in product(*products):
    print(prod)