Is it possible to write a list comprehension for the following loop?
m = []
counter = 0
for i, x in enumerate(l):
if x.field == 'something':
counter += 1
m.append(counter / i)
I do not know how to increment the counter inside the list comprehension.
The count() is a built-in function in Python. It will return you the count of a given element in a list or a string. In the case of a list, the element to be counted needs to be given to the count() function, and it will return the count of the element. The count() method returns an integer value.
Short answer: you can count the number of elements x that match a certain condition(x) by using the one-liner expression sum(condition(x) for x in lst) . This creates a generator expression that returns True for each element that satisfies the condition and False otherwise.
Yes, the list comprehension preserves the order of the original iterable (if there is one). If the original iterable is ordered (list, tuple, file, etc.), that's the order you'll get in the result. If your iterable is unordered (set, dict, etc.), there are no guarantees about the order of the items.
You could use an itertools.count
:
import itertools as IT
counter = IT.count(1)
[next(counter)/i for i, x in enumerate(l) if x.field == 'something']
To avoid the possible ZeroDivisionError pointed out by tobias_k, you could make enumerate
start counting from 1 by using enumerate(l, start=1)
:
[next(counter)/i for i, x in enumerate(l, start=1)
if x.field == 'something']
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