Conditional itertools.product

问题描述 投票:0回答:2

假设我有一个重物清单,为了论证考虑x = numpy.arange(10)/10

我通过gen = itertools.product(x,x)创建了一个生成器,以执行一些计算。事实是我的计算是对称的:对于所有ijheavy_calc(x[i],x[j]) = heavy_calc(x[j],x[i])

因此,我只想计算矩阵的上半部分。我怎样才能使生成器仅在(x[i], x[j])时返回i >= j

python numpy generator
2个回答
1
投票

我会生成生成器手工

def gen(x):
    for i in range(len(x)):
        for y in x[i:]:
            yield(x[i], y)

它按预期提供:

>>> list(gen(list(range(4))))
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]

0
投票

使用itertools.combinations_with_replacement,而不是product

gen = itertools.combinations_with_replacement(x, 2)

注意,这会给(x[i], x[j])元组加上i <= j,而不是i >= j。对于您的用例来说应该没问题。

© www.soinside.com 2019 - 2024. All rights reserved.