【发布时间】:2010-07-01 00:04:54
【问题描述】:
我猜这是一个学术问题,但第二个结果对我来说没有意义。不应该和第一次一样彻底空吗?这种行为的基本原理是什么?
from itertools import product
one_empty = [ [1,2], [] ]
all_empty = []
print [ t for t in product(*one_empty) ] # []
print [ t for t in product(*all_empty) ] # [()]
更新
感谢所有的答案——非常有用。
维基百科对Nullary Cartesian Product 的讨论提供了明确的声明:
无集的笛卡尔积... 是包含 空元组。
下面是一些代码,您可以使用这些代码来处理富有洞察力的answer from sth:
from itertools import product
def tproduct(*xss):
return ( sum(rs, ()) for rs in product(*xss) )
def tup(x):
return (x,)
xs = [ [1, 2], [3, 4, 5] ]
ys = [ ['a', 'b'], ['c', 'd', 'e'] ]
txs = [ map(tup, x) for x in xs ] # [[(1,), (2,)], [(3,), (4,), (5,)]]
tys = [ map(tup, y) for y in ys ] # [[('a',), ('b',)], [('c',), ('d',), ('e',)]]
a = [ p for p in tproduct( *(txs + tys) ) ]
b = [ p for p in tproduct( tproduct(*txs), tproduct(*tys) ) ]
assert a == b
【问题讨论】:
标签: python itertools cross-product