'Improving (shortening) my list comprehension with lambda x function?
!!! I know I could use Counter() here, but that's not the point !!!
Giving the code below:
test =[['a',1],['a',2],['b',3], ['c',5],['a',7],['c',9]]
{i:[test[x][0] for x in range(len(test))].count(i) for i in [test[x][0] for x in range(len(test))]}
output: {'a': 3, 'b': 1, 'c': 2}
Is there a way to avoid repeating the sequence without creating another variable:
[test[x][0] for x in range(len(test))]
Solution 1:[1]
from itertools import groupby
test =[['a',1],['a',2],['b',3], ['c',5],['a',7],['c',9]]
{key: sum(j[1] for j in i) for key, i in groupby(test, key=lambda x: x[0])}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Vovin |