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