2

我敢肯定它已经被问过了,它会得到一个“只使用生成器理解!” 响应,但以防万一它在某个地方的标准库中,而我只是在 itertools 中找不到它......

在 Python 3.x 中,是否有以下功能替代方案:

(x if c else y for c, x, y in zip(cs, xs, ys))

例如,numpy.where(cs, xs, ys)正是这样做的。

4

2 回答 2

2

这是一个生成器表达式,所以只需打开它:

cs = [True, False, True]
xs = [1, 2, 3]
ys = [10, 20, 30]

def generator(cs, xs, ys):
    for c, x, y in zip(cs, xs, ys):
        yield x if c else y

print(list(x if c else y for c, x, y in zip(cs, xs, ys)))
print(list(generator(cs, xs, ys)))

输出:

[1, 20, 3]
[1, 20, 3]
于 2013-01-22T16:07:41.227 回答
1

嗯,这样的事情怎么办?(我在 Python 2.7.3 中,但我认为这并不重要。)

>>> import itertools as it
>>> a=[1,2,3]
>>> b=[10,20,30]
>>> cond=[True, False, True]
>>> func=lambda c,x,y: x if c else y
>>> test=it.starmap(func, it.izip(cond,a,b))
>>> test.next()
1
>>> test.next()
20
>>> test.next()
3
于 2013-01-22T15:27:57.920 回答