简体   繁体   中英

How can I combine a tuple elements into a list in python

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.

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

before Python 3.5

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM