Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop for each item in a list

I have a dictionary:

mydict = {'item1':[1,2,3],'item2':[10,20,30]}

I want to create the cartesian product of the two so that I get a tuple of each possible pair.

output: [(1,10),(1,20),(1,30),
         (2,10),(2,20),(2,30),
         (3,10),(3,20),(3,30)]

It seems like there would be a simple way to do this so that it extends if I have three items. Kind of like a dynamic number of loops. Feels like I am missing an obvious way to do this...

like image 962
Chris Avatar asked May 14 '15 01:05

Chris


People also ask

How can you loop through all the items in the list?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.

Can we use for loop for list?

Using Python for loop to iterate over a list. In this syntax, the for loop statement assigns an individual element of the list to the item variable in each iteration. Inside the body of the loop, you can manipulate each list element individually.

Can you use a list in a for loop Python?

You can use a for loop to create a list of elements in three steps: Instantiate an empty list. Loop over an iterable or range of elements. Append each element to the end of the list.


2 Answers

The itertools.product() function will do this:

>>> import itertools
>>> mydict = {'item1':[1,2,3],'item2':[10,20,30]}
>>> list(itertools.product(*mydict.values()))
[(10, 1), (10, 2), (10, 3), (20, 1), (20, 2), (20, 3), (30, 1), (30, 2), (30, 3)]

If you need to control the order of the resulting tuples, you can do

itertools.product(mydict['item1'], mydict['item2'])
like image 112
Greg Hewgill Avatar answered Sep 27 '22 20:09

Greg Hewgill


You can also brute force it using two loops

mydict = {'item1':[1,2,3],'item2':[10,20,30]}

x = []
for i in mydict['item1']:
    for j in mydict['item2']:
        x.append((i,j))

All this code does is go through all of the item in mydict['item1'], then through each item in mydict['item2'], then appends a pair of each to a new list.

It will give you this result:

[(1, 10), (1, 20), (1, 30), (2, 10), (2, 20), (2, 30), (3, 10), (3, 20), (3, 30)]
like image 25
michaelpri Avatar answered Sep 27 '22 20:09

michaelpri