Meph
Meph

Reputation: 532

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.

Upvotes: 5

Views: 645

Answers (4)

unni
unni

Reputation: 2991

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.

Upvotes: 2

Sven Marnach
Sven Marnach

Reputation: 602365

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')

Upvotes: 7

sth
sth

Reputation: 229784

You could implement it with a recursive function:

def combis(ls):
   if not ls:
      yield []
      return
   (name, limit) = ls[-1]
   for start in combis(ls[:-1]):
      for c in range(1, limit+1):
         yield start + [(name, c)]

Upvotes: 1

Anuj
Anuj

Reputation: 9632

For implementing something like this the complexity of the program would be very high. try reworking out the logic so that you can reduce the complexity ..

Upvotes: -1

Related Questions