gpt4 book ai didi

python - 如何从具有子元组的元组创建列表?

转载 作者:行者123 更新时间:2023-11-28 21:38:32 25 4
gpt4 key购买 nike

我有两个列表 ab。然后我创建所有组合,采用 a 的所有双长度组合加上 b 中的每一个:

import itertools as it

a = [1,2,3,4]
b = [5,6]

for i in it.product(it.combinations(a, 2), b):
print (i)

# output:
((1, 2), 5)
((1, 2), 6)
((1, 3), 5)
...

# expected output:
[1, 2, 5]
[1, 2, 6]
[1, 3, 5]
...

元组如何在循环操作阶段转化为列表?

最佳答案

以下理解将起作用:

>>> [[*x, y] for x, y in it.product(it.combinations(a, 2), b)]  # Py3
>>> [list(x) + [y] for x, y in it.product(it.combinations(a, 2), b)] # all Py versions
[[1, 2, 5],
[1, 2, 6],
[1, 3, 5],
[1, 3, 6],
[1, 4, 5],
[1, 4, 6],
[2, 3, 5],
[2, 3, 6],
[2, 4, 5],
[2, 4, 6],
[3, 4, 5],
[3, 4, 6]]

关于python - 如何从具有子元组的元组创建列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48101672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com