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

标签 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

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

最佳答案

使用 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/

相关文章:

python - (osx) ffmpeg 将 mp3 和 png 合并为 mp4,生成没有音频的 mp4

python - 如何解析时间

list - 如何实现 not_all_equal/1 谓词

python - 删除 pandas 中的 html 标签

python - 在 Django 中,如何立即将组的创建者添加到该组?

python - Q设置(): How to save to current working directory

python - 如何在 Python 中为矩阵/嵌套列表的每个元素加 1?

c# - 将静态列表分配给非静态列表

python - 在 VM 中通过 Python3 运行 IPython Notebook

python - TCP 收到的数据偶尔会错位