2

I have the following lists:

list1 = [ 'A','B','C']
list2 = [ '1', '2' ]

Trying to generate a new list of tuples with the following desired result:

[(A1),(A2),(A1,B1),(A1,B2),(A2,B1),(A2,B2),(A1,B1,C1),(A2,B1,C1)...]

Each tuple will eventully be used to write a single line in an output file.
Note that:

  1. In each tuple, each letter from list1, if defined, must be defined after the preceding letters. for example, if 'B' is defined in a tuple then 'A' must be in the tuple as well and prior to 'B'. tuple (A1,C1) is not desired since 'B' is not defined as well.
  2. Tuples must be unique.
  3. list1 & list2 are just an example and may vary in length.

I tried playing around with itertools, specifically with, product, permutations, combinations for quite some time. I can't seem to pull it off and I don't even have some code worth sharing.

idanshmu
  • 5,061
  • 6
  • 46
  • 92

2 Answers2

2

Take successive larger slices of list1, and use products of products:

from itertools import product

elements = []
for letter in list1:
    elements.append([''.join(c) for c in product(letter, list2)])
    for combo in product(*elements):
        print combo

The elements list is grown each loop, adding another set of letter + numbers list to produce products from.

This produces:

>>> elements = []
>>> for letter in list1:
...     elements.append([''.join(c) for c in product(letter, list2)])
...     for combo in product(*elements):
...         print combo
... 

('A1',)
('A2',)
('A1', 'B1')
('A1', 'B2')
('A2', 'B1')
('A2', 'B2')
('A1', 'B1', 'C1')
('A1', 'B1', 'C2')
('A1', 'B2', 'C1')
('A1', 'B2', 'C2')
('A2', 'B1', 'C1')
('A2', 'B1', 'C2')
('A2', 'B2', 'C1')
('A2', 'B2', 'C2')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

What about this:

from itertools import product

output = []
for z in [list1[:n+1] for n in range(len(list1))]:
   for y in product(list2, repeat=len(z)):
      output.append(tuple(''.join(u) for u in zip(z, y)))

print(output)
richsilv
  • 7,993
  • 1
  • 23
  • 29