gpt4 book ai didi

python - 通过组合元组元素获取元组列表的产品?

转载 作者:太空狗 更新时间:2023-10-30 02:43:04 24 4
gpt4 key购买 nike

我有一个元组列表,我试图通过组合各个元组元素来获取其乘积。

例如:

lists = [
[(1,), (2,), (3,)],
[(4,), (5,), (6,)]
]
p = itertools.product(*lists)
for product in p:
print product

这会产生一堆元组的元组:

((1,), (4,))
((1,), (5,))
((1,), (6,))
((2,), (4,))
((2,), (5,))
((2,), (6,))
((3,), (4,))
((3,), (5,))
((3,), (6,))

我想要的是像这样的元组列表:

(1,4)
(1,5)
(1,6)
(2,4)
(2,5)
(2,6)
(3,4)
(3,5)
(3,6)

我还需要它来保存任意数量的元组初始列表。

所以在 3 的情况下:

lists = [
[(1,), (2,), (3,)],
[(4,), (5,), (6,)],
[(7,), (8,), (9,)]
]
p = itertools.product(*lists)
for product in p:
print product

我愿意:

(1, 4, 7)
(1, 4, 8)
(1, 4, 9)
(1, 5, 7)
(1, 5, 8)
(1, 5, 9)
(1, 6, 7)
(1, 6, 8)
(1, 6, 9)
(2, 4, 7)
(2, 4, 8)
(2, 4, 9)
(2, 5, 7)
(2, 5, 8)
(2, 5, 9)
(2, 6, 7)
(2, 6, 8)
(2, 6, 9)
(3, 4, 7)
(3, 4, 8)
(3, 4, 9)
(3, 5, 7)
(3, 5, 8)
(3, 5, 9)
(3, 6, 7)
(3, 6, 8)
(3, 6, 9)

最佳答案

您可以简单地使用 itertools.chain.from_iterable像这样压平内部元组

for product in p:
print tuple(itertools.chain.from_iterable(product))

例如,

>>> from itertools import chain, product
>>> [tuple(chain.from_iterable(prod)) for prod in product(*lists)]
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

关于python - 通过组合元组元素获取元组列表的产品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34668424/

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