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:
- 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. - Tuples must be unique.
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.
2 Answers 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')
-
I missed a step here. :-)Martijn Pieters– Martijn Pieters2014年01月07日 15:00:59 +00:00Commented Jan 7, 2014 at 15:00
-
@Nabla: there, fixed it.Martijn Pieters– Martijn Pieters2014年01月07日 15:04:32 +00:00Commented Jan 7, 2014 at 15:04
-
Yes, I see that now, looking into it.Martijn Pieters– Martijn Pieters2014年01月07日 15:06:46 +00:00Commented Jan 7, 2014 at 15:06
-
Hi, 10x for the solution. however there is a glitch in it. if you change list1, to [A,bb,C] the result are not as excepted. your solution assumes list1 contain item of length 1 only.idanshmu– idanshmu2014年01月07日 15:33:02 +00:00Commented Jan 7, 2014 at 15:33
-
@idanshmu: put square brackets around the
letter
:product([letter], list2)
.Martijn Pieters– Martijn Pieters2014年01月07日 15:35:03 +00:00Commented Jan 7, 2014 at 15:35
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)