如何生成类似于
[(), (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测试过的产品,我只是不能将元组的组合合并成一个。
你知道怎么把这件事做得干净吗?谢谢!
发布于 2014-04-11 12:49:52
请注意,单个元素元组的表示方式类似于这个(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)]发布于 2014-04-11 13:02:23
如果您不想使用任何特殊的导入:
start = 1; limit = 10
[ range(start, start + x) for x in range(limit) ]对于start = 1,输出是:
[[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8, 9]]
如果您想使用该产品,也许使用itertools可能是最优雅的。
发布于 2014-04-11 13:02:44
你可以这样做,
>>> a=[(), (1,), (1,2), (1,2,3)]
>>> b=[(), (4,), (4,5), (4,5,6)]
>>> for ix in a:
... for iy in b:
... print ix + iy
...
()
(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)https://stackoverflow.com/questions/23012931
复制相似问题