This is an old question. The answer is: you can't (or if you can, you shouldn't).
But there is a flaw in your idea (that's why I write this answer): you are using the wrong tool. I'm not talking of collections.Counter
, but of functional tools. List comprehensions is a:
a syntactic construct available in some programming languages for creating a list based on existing lists. (Wikipedia)
Here, you want to create a list based on an existing list and on the current state of your list. This could not be, by definition, a list comprehension by the book.
But there is another functional construction that is perfectly suitable for this case: the fold. A fold:
through use of a given combining operation, recombine the results of recursively processing its constituent parts, building up a return value (Wikipedia)
In Python, you have to use the reduce
function of the functools
module:
>>> generator = (i%7 for i in range(20))
>>> import functools
>>> functools.reduce(lambda resources, resource: {**resources, resource: resources.get(resource, 0) + 1}, generator, {})
{0: 3, 1: 3, 2: 3, 3: 3, 4: 3, 5: 3, 6: 2}
The combining function takes the current dictionary and replaces the value associated to resource
by the previous value + 1.
Of course, a regular loop would be okay too.