5

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.

user2297037
  • 1,167
  • 2
  • 14
  • 34
  • 2
    Note that this can result in division by zero if the first (i.e. "zeroth") element satisfies the condition. Also, what exactly are you trying to achieve? – tobias_k Jan 05 '15 at 11:36
  • You are right. I wrote that code on the fly and I forget to increment by 1 i. I want to compute the [average precision](https://en.wikipedia.org/wiki/Information_retrieval#Average_precision) – user2297037 Jan 05 '15 at 11:43

1 Answers1

11

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']
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677