5
我在试图找到两个不同集合的笛卡尔乘积。我无法在网上找到有关笛卡尔产品的列表或词典。Power set和笛卡尔积python的产品
功率设置也很混乱。
这些都不在我的书中,我一直在使用。
亚勒可能会指出我正确的方向。
我在试图找到两个不同集合的笛卡尔乘积。我无法在网上找到有关笛卡尔产品的列表或词典。Power set和笛卡尔积python的产品
功率设置也很混乱。
这些都不在我的书中,我一直在使用。
亚勒可能会指出我正确的方向。
对于笛卡尔产品,请查看itertools.product
。
对于幂,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?再次感谢! – bradb 2012-04-26 23:56:26
是的,您需要从'itertools''导入您使用的函数,就像您从另一个模块使用的任何函数一样。 – 2012-04-26 23:58:38
powerset可能更好地定义为's = set(iterable)'。 – Darthfett 2012-04-26 23:59:37