参数数目未知的手动产品

2024-07-03 07:16:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

B

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

当我不知道参数n的个数时,如何计算笛卡尔积

我问这个问题的原因:

考虑一下这段代码:

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,我将避免大量的比较和求和


Tags: in示例列表forif字典helpproduct
2条回答

你可以做:

items = ["abcd","xy"]

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

列表items可以包含任意数量的字符串,使用product的计算将为您提供这些字符串的笛卡尔积

请注意,您不必将其转换为一个列表-您可以对其进行迭代,并在不再希望继续时停止:

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

如果您只想在达到某个条件后中止分配,并且希望避免从笛卡尔积中为这些条件生成所有元素,那么首先就不要列出所有组合

itertools.productlazy,这意味着它一次只生成笛卡尔积的一个值。所以你不需要生成所有的元素,也不需要比较元素。只是不要对结果调用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)

因此,从iterables的左侧可以得到一个递增的模式。因此,请确保您对iterables的排序方式能够正确指定中断条件

相关问题 更多 >