【发布时间】:2012-05-07 17:56:37
【问题描述】:
我试图找到两个不同集合的笛卡尔积。我在网上找不到任何关于集合的笛卡尔积的任何东西,它要么是列表,要么是字典。
而且电源组也很混乱。
这些都没有在我一直在使用的书中。
你们中的一个能否指出我正确的方向。
【问题讨论】:
标签: python python-3.x
我试图找到两个不同集合的笛卡尔积。我在网上找不到任何关于集合的笛卡尔积的任何东西,它要么是列表,要么是字典。
而且电源组也很混乱。
这些都没有在我一直在使用的书中。
你们中的一个能否指出我正确的方向。
【问题讨论】:
标签: python python-3.x
对于笛卡尔积,请查看itertools.product。
对于powerset,the itertools docs也给我们一个秘诀:
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
例如:
>>> test = {1, 2, 3}
>>> list(powerset(test))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
>>> list(product(test, test))
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
【讨论】:
itertools导入你使用的函数,就像你从另一个模块使用的任何函数一样。
s = set(iterable) 可能会更好地定义。