Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - keeping counter inside list comprehension

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.

like image 956
user2297037 Avatar asked Jan 05 '15 11:01

user2297037


People also ask

How do you count a value in a list Python?

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.

How do you count elements in a list with conditions in Python?

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.

Does Python list comprehension maintain order?

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.


1 Answers

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']
like image 159
unutbu Avatar answered Oct 07 '22 03:10

unutbu