Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to shorten this Python generator expression?

I need to build a generator and I was looking for a way to shorten this for loop into a single line. I tried enumerate but that did not work.

counter=0
for element in string:
    if function(element):
        counter+=1
        yield counter
    else:
        yield counter
like image 338
garlfd Avatar asked Apr 30 '13 23:04

garlfd


People also ask

How do you shorten a function in Python?

The shorten() function This function of the textwrap module is used truncate the text to fit in the specified width. For example, if you want to create a summary or preview, use the shorten() function. Using shorten() , all the whitespaces in your text will get standardized into a single space.

How do I find the length of a generator in Python?

To get the length of a generator in Python:Use the list() class to convert the generator to a list. Pass the list to the len() function, e.g. len(list(gen)) . Note that once the generator is converted to a list, it is exhausted.

What is a generator expression in Python?

Python generators are a simple way of creating iterators. All the work we mentioned above are automatically handled by generators in Python. Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).

Is generator faster than list comprehension?

List comprehensions return the entire list, and the generator expression returns only the generator object. The values will be the same as those in the list, but they will be accessed one at a time by using the next() function. This is what makes list comprehensions faster than generator expressions.


1 Answers

counter=0
for element in string:
    counter+=bool(function(element))
    yield counter

(Yes, adding Booleans to ints works exactly as if True was 1 and False was 0).

The bool() call is only necessary if function() can have return values other than True, False, 1, and 0.

like image 112
Andrew Clark Avatar answered Sep 28 '22 13:09

Andrew Clark