参数数量未知的手动产品

Manual product with unknown number of arguments

以下示例给出了相同的结果:

A.

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是另一个分配给元组的字典帮助一些数值。

由于策略值已排序,我知道 if 语句在某个 alloc 后将不再为真。由于分配是一个相当大的列表,如果我可以使用示例算法 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 is lazy 表示它一次只会生成一个笛卡尔积的值。所以你永远不需要生成所有元素,你也永远不需要比较元素。只是不要对结果调用 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)

所以你从你的可迭代对象的左侧得到了一个递增的模式。因此,请确保以可以正确指定中断条件的方式对可迭代对象进行排序。