2

I'm sure it's been asked and it's going to get a "just use a generator comprehension!" response, but just in case it's in the standard library somewhere and I just can't find it in itertools...

In Python 3.x, is there a functional alternative to:

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

For example, numpy.where(cs, xs, ys) does exactly this.

4

2 に答える 2

2

It's a generator expression, so just unwrap it:

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)))

Output:

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

Hmm, what about something like this? (I'm in Python 2.7.3, but I don't think it matters here.)

>>> 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 に答える