我想这是一个学术问题,但第二个结果对我来说没有意义。不应该和第一次一样彻底空吗?这种行为的理由是什么?
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) ] # [()]
更新
感谢所有的答案 - 非常有用。
Wikipedia 对Nullary Cartesian Product的讨论提供了明确的声明:
无集合的笛卡尔积 ... 是包含空元组的单例集合。
以下是一些代码,您可以使用这些代码来解决 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