Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: all possible combinations of "dynamic" list

I really can't find this out. I tried to use itertools, tried all kind of looping, but still i can't achieve what I want. Here is what i need:

I have list such as:

list = [("car", 2), ("plane", 3), ("bike", 1)]

This list is each time different, there can be 5 different items in it each time and what I need is to get something like this:

car1, plane1, bike1
car1, plane2, bike1
car1, plane3, bike1
car2, plane1, bike1
car2, plane2, bike1
car2, plane3, bike1

I am really lost. It is obvious it will be probably something very simple, but I am unable to solve it.

like image 356
Meph Avatar asked Oct 27 '11 10:10

Meph


2 Answers

You could use itertools.product():

my_list = [("car", 2), ("plane", 3), ("bike", 1)]
a = itertools.product(*([name + str(i + 1) for i in range(length)] 
                        for name, length in my_list))
for x in a:
    print x

prints

('car1', 'plane1', 'bike1')
('car1', 'plane2', 'bike1')
('car1', 'plane3', 'bike1')
('car2', 'plane1', 'bike1')
('car2', 'plane2', 'bike1')
('car2', 'plane3', 'bike1')
like image 125
Sven Marnach Avatar answered Nov 12 '22 22:11

Sven Marnach


Try this:

L = [("car", 2), ("plane", 3), ("bike", 1)]
O = []
N = []
for each in L:
  O.append(each[0])
  N.append(each[1])
for each in O:
  strin = ""
  for item in N:
     strin = strin + item + each + ","

  print strin[:-1]

Since your list will contain only five items utmost, this is a plausible solution.

like image 42
unni Avatar answered Nov 12 '22 22:11

unni