如何生成类似的东西
[(), (1,), (1,2), (1,2,3)..., (1,2,3,...n)]
和
[(), (4,), (4,5), (4,5,6)..., (4,5,6,...m)]
然后取它们的乘积并合并到
[(), (1,), (1,4), (1,4,5), (1,4,5,6), (1,2), (1,2,4)....(1,2,3,...n,4,5,6,...m)]
?
对于前两个列表,我尝试了 https://docs.python.org/2/library/itertools.html#recipes 中的 powerset 配方, 但会有一些我不想要的东西,比如 (1,3), (2,3)
对于我用 chain
和 product
测试过的产品,但我无法将元组的组合合并为一个。
知道如何做到这一点吗?谢谢!
最佳答案
请注意,单元素元组表示为 (1,)
。
a = [(), (1,), (1, 2), (1, 2, 3)]
b = [(), (4,), (4, 5), (4, 5, 6)]
from itertools import product
for item1, item2 in product(a, b):
print item1 + item2
输出
()
(4,)
(4, 5)
(4, 5, 6)
(1,)
(1, 4)
(1, 4, 5)
(1, 4, 5, 6)
(1, 2)
(1, 2, 4)
(1, 2, 4, 5)
(1, 2, 4, 5, 6)
(1, 2, 3)
(1, 2, 3, 4)
(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5, 6)
如果你想把它们放在一个列表中,你可以像这样使用列表理解
from itertools import product
print [sum(items, ()) for items in product(a, b)]
或者更简单,
print [items[0] + items[1] for items in product(a, b)]
关于python - 使用python生成格子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23012931/