簡體   English   中英

參數數量未知的手動產品

[英]Manual product with unknown number of arguments

以下示例給出了相同的結果:

一種。

product = []
for a in "abcd":
    for b in "xy":
        product.append((a,b))

B.

from itertools import product
list(product("abcd","xy"))

當我不知道參數n時如何計算例A中的笛卡爾積?

原因我問這個:

考慮這段代碼:

allocations = list(product(*strategies.values()))
for alloc in allocations:
    PWC[alloc] = [a for (a,b) in zip(help,alloc) if coalitions[a] >= sum(b)]

strategies詞典的值是元組列表, help是輔助變量(每個alloc具有相同長度的列表),而coalitions是另一個在help中分配給元組一些數值的詞典。

由於對策略值進行了排序,因此我知道,在某個alloc之后,if語句將不再成立。 由於分配是一個很大的列表,因此,如果可以使用示例算法A,我將避免大量的比較和大量的求和。

你可以做:

items = ["abcd","xy"]

from itertools import product
list(product(*items))

列表items可以包含任意數量的字符串,使用product進行計算將為您提供這些字符串的笛卡爾乘積。

請注意,您不必將其變成列表-您可以對其進行迭代,並在不再希望繼續時停止:

for item in product(*items):
    print(item)
    if condition:
        break

如果您只是想在達到特定條件后中止分配,並且想要避免從笛卡爾乘積中為這些元素生成所有元素,那么根本就不用列出所有組合。

itertools.product惰性的 ,這意味着它一次只會生成一個笛卡爾積的單個值。 因此,您無需生成所有元素,也不需要再比較這些元素。 只是不要在結果上調用list() ,因為那樣會迭代整個序列並將所有可能的組合存儲在內存中:

allocations = product(*strategies.values())
for alloc in allocations:
    PWC[alloc] = [a for (a,b) in zip(help,alloc) if coalitions[a] >= sum(b)]

    # check whether you can stop looking at more values from the cartesian product
    if someCondition(alloc):
        break

重要的是要注意itertools.product如何生成值,遵循的模式。 它基本上等效於以下內容:

for a in firstIterable:
    for b in secondIterable:
        for c in thirdIterable:
            …
                for n in nthIterable:
                    yield (a, b, c, …, n)

因此,您從可迭代對象的左側獲得越來越多的模式。 因此,請確保以正確指定中斷條件的方式訂購可迭代對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM