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
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.
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.
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).
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With