如何将元组元素组合到python中的列表中

时间:2017-07-05 09:13:01

标签: python list python-3.x tuples

请考虑以下代码:

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

我的目标结果如下:

[['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']]

但上面代码的结果是:

None
None
None
None
None
None
None
None

我需要对代码进行哪些必要的更正?提前谢谢。

1 个答案:

答案 0 :(得分:3)

使用itertools.product,解包和列表理解

[[l[0], l[2], *l[1]] for l in itertools.product(list1, list3, list2)]

[[l1, l2, *l3] for l1, l3, l2 in itertools.product(list1, list3, list2)]
在Python 3.5之前的

对于Python 3.5之前的版本,您可以执行类似这样的操作

[[l1, l2] + list(l3) for l1, l3, l2 in itertools.product(list1, list3, list2)]

如果您知道l3只包含2个元素,您可以使用嵌套解包,如@ShadowRanger所述

[[a, b, c1, c2] for a, (c1, c2), b in itertools.product(list1, list3, list2)]