Reputation: 75
Consider the following code below:
list1 = ['1x', '2x']
list2 = ['x18', 'x74']
list3 = [('100p1', '100p2'), ('300p1', '300p2')]
gen_list = [[a,b] for a in list1 for b in list2]
for new_list in gen_list:
for c in list3:
print(new_list.extend(c))
My target result is like this:
[['1x','x18, '100p1', '100p2'],
['1x','x74, '100p1', '100p2'],
['1x','x18, '300p1', '300p2'],
['1x','x74, '300p1', '300p2'],
['2x','x18, '100p1', '100p2'],
['2x','x74, '100p1', '100p2'],
['2x','x18, '300p1', '300p2'],
['2x','x74, '300p1', '300p2']]
but the result of the above code is this:
None
None
None
None
None
None
None
None
What necessary correction do I need to apply on my code? Thanks in advance.
Upvotes: 1
Views: 90
Reputation: 7058
using itertools.product, unpacking and a list comprehension
[[l[0], l[2], *l[1]] for l in itertools.product(list1, list3, list2)]
or
[[l1, l2, *l3] for l1, l3, l2 in itertools.product(list1, list3, list2)]
For versions before Python 3.5 you could do something like this
[[l1, l2] + list(l3) for l1, l3, l2 in itertools.product(list1, list3, list2)]
If you know l3 only contains 2 elements you can use nested unpacking, as mentioned by @ShadowRanger
[[a, b, c1, c2] for a, (c1, c2), b in itertools.product(list1, list3, list2)]
Upvotes: 3