Python: all possible combinations of a "dynamic" list

I really can’t find out. I tried using itertools, tried all kinds of loops, but still I cannot achieve what I want. This is what I need:

I have a list, for example:

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

This list is different every time, every time there can be 5 different elements in it, and I need 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. Obviously, this will probably be something very simple, but I cannot solve it.

+5
source share
4 answers

You can 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')
+7
source

Try the following:

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]

, .

+2

:

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)]
+1

To implement something like this, the complexity of the program will be very high. try reworking the logic to reduce complexity.

-1
source

All Articles