简体   繁体   中英

how do I iterate through a list of lists

I am trying to figure out how to iterate through a list of list and record all possible combinations within the list from left to right. The first list is always going to be the first position of the combination, the second list will be the second position, and etc.

How would I get all possible combinations of the letters assuming that the first list is the same letter always. So far my code does isolate the first set but I am having trouble appending the rest onto the list to create the combinations.

listoflists = [[a,b,c,d][e,f,g][h,i]]

for i in range(len(listoflists[]):
    for j in range(len(listoflists[i])):
        if(i==0):
            print(listoflists[i][j])
            newlist[i].append([listoflists[i][j]])
        else:
            print(i)
            print(listoflists[i][j])
            #newlist[[i[j]].append([listoflists[i][j]])

The last line of code throws an error and the print statement are there for debugging. So how exactly would i get all the combinations of the list of lists using for loops

That process is called cartesian product :

In mathematics, a Cartesian product is a mathematical operation which returns a set (or product set or simply product) from multiple sets. That is, for sets A and B, the Cartesian product A × B is the set of all ordered pairs (a, b) where a ∈ A and b ∈ B.

There is already a library function in python for that, namely itertools.product :

From documentation :

itertools.product(*iterables[, repeat]) Cartesian product of input iterables.

Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

When you apply it to your list, you get your desired result:

>>> import itertools
>>> ll = [["a","b","c","d"], ["e","f","g"], ["h","i"]]
>>> list(itertools.product(*ll))
[('a', 'e', 'h'), ('a', 'e', 'i'), ('a', 'f', 'h'), ('a', 'f', 'i'), ('a', 'g', 'h'), ('a', 'g', 'i'), ('b', 'e', 'h'), ('b', 'e', 'i'), ('b', 'f', 'h'), ('b', 'f', 'i'), ('b', 'g', 'h'), ('b', 'g', 'i'), ('c', 'e', 'h'), ('c', 'e', 'i'), ('c', 'f', 'h'), ('c', 'f', 'i'), ('c', 'g', 'h'), ('c', 'g', 'i'), ('d', 'e', 'h'), ('d', 'e', 'i'), ('d', 'f', 'h'), ('d', 'f', 'i'), ('d', 'g', 'h'), ('d', 'g', 'i')]

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