Is there a way to shorten this Python generator expression?

I need to build a generator, and I was looking for a way to shorten this for a single line loop. I tried to list, but it did not work.

counter=0
for element in string:
    if function(element):
        counter+=1
        yield counter
    else:
        yield counter
+5
source share
4 answers
counter=0
for element in string:
    counter+=bool(function(element))
    yield counter

(Yes, adding Booleans to ints works exactly as if it Truewere 1and Falsewas 0).

The call bool()is necessary only if function()can have return values that are different from True, False, 1and 0.

+6
source

If you are using Python 3, you can do:

from itertools import accumulate

yield from accumulate(1 if function(x) else 0 for x in string)

. , , .

+4

function:

truths = (function(x) for x in string)

Then you can match them with 0s and 1s:

onesandzeroes = (1 if function(x) else 0 for x in string)

And then accumulate them:

running = itertools.accumulate(1 if function(x) else 0 for x in string)

As docs notes, it accumulatewas added in Python 3.2. If you are using 2.x, you can copy and paste the “Equivalent” recipe into documents. (If you are using 3.0-3.1, you can do the same, but in fact, in this case, just upgrade.)

+4
source

You can shorten it to:

counter=0
for element in string:
    if function(element):
        counter+=1
    yield counter
+3
source

All Articles