Reputation: 1194
Is there a way to aggregate the value of each entry of a list using Counter
, and not just count the number of time an entry is present ?
For example, if I have a list
from collections import Counter
lst = [
['John', 1],
['James', 2],
['John', 3],
['Andy', 1]
]
and I do
total = Counter(name for name, num in lst)
print(total)
The output will be
Counter({'John': 2, 'James': 1, 'Andy': 1})
Which is expected. I was just wondering if there's a way to obtain
Counter({'John': 4, 'James': 2, 'Andy': 1})
I know there are many ways to do it, but I'm looking for a way to do it with Counter
.
Upvotes: 2
Views: 166
Reputation: 5324
You need to loop through the list and update the counter accordingly.
c = Counter()
for k, v in lst:
c.update({k: v})
>>> print(c)
Counter({'John': 4, 'James': 2, 'Andy': 1})
You can also use a list comprehension, but using a comprehension for side effects is not recommended:
[c.update({k: v}) for k, v in lst]
print(c)
Output is the same.
Upvotes: 2
Reputation: 33007
You can use a simple loop to add the values:
total = Counter()
for name, num in lst:
total[name] += num
print(total) # -> Counter({'John': 4, 'James': 2, 'Andy': 1})
If there's a way to do this in one line in O(n), I'd love to know.
Upvotes: 2
Reputation: 17156
Adding another level of for loop to posted list comprehension
total = Counter(name for name, num in lst for _ in range(num))
print(total)
# Output: Counter({'John': 4, 'James': 2, 'Andy': 1})
Upvotes: 2