考虑下面的代码:
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
我需要对我的代码进行哪些必要的更正?提前致谢。
最佳答案
使用 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)]
关于python - 如何将元组元素组合到Python中的列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44921847/