I have 3 lists:
['1','2']
['a','b','c']
['X','Y']
and the result I am looking to get:
['1aX','1bX','1cX','2aX','2bX','2cX','1aY','1bY','1cY','2aY','2bY','2cY']
is there a way to set this up quickly?
I have 3 lists:
['1','2']
['a','b','c']
['X','Y']
and the result I am looking to get:
['1aX','1bX','1cX','2aX','2bX','2cX','1aY','1bY','1cY','2aY','2bY','2cY']
is there a way to set this up quickly?
You can use itertools.product()
:
map("".join, itertools.product(list1, list2, list3))
>>> x,y,z=['1','2'],['a','b','c'],['x','y']
>>> s=[a+b+c for c in z for a in x for b in y]
>>> s
['1ax', '1bx', '1cx', '2ax', '2bx', '2cx', '1ay', '1by', '1cy', '2ay', '2by', '2cy']
This way you can choose the order you want
To get the exact result that you specified, you can use the following:
import operator
import itertools
list1 = ['1','2']
list2 = ['a','b','c']
list3 = ['X','Y']
getter = operator.itemgetter(1, 2, 0)
result = [''.join(getter(seq)) for seq in itertools.product(list3, list1, list2)]
The final argument to itertools.product()
will be the first to change, so based on your example output we want list2
to be last, then list1
, and then list3
, since first the middle element advances, then the first element, then the last. The operator.itemgetter()
call is used to reorder the elements so that the element from list1
comes first, etc.
I find list comprehensions easier to read here, but here is a one-line alternative that uses map()
:
map(''.join, map(operator.itemgetter(1, 2, 0), itertools.product(list3, list1, list2)))
(You could do the list comprehension in one line as well, but you shouldn't because then the operator.itemgetter()
call would be executed on each iteration)