This commit is contained in:
Angelos Chalaris
2019-09-22 15:21:54 +03:00
committed by GitHub
parent 6f1d64827b
commit ab3c44a5d5

View File

@ -10,14 +10,11 @@ Use list comprehension to map each element to the appropriate `key`.
```py ```py
def group_by(lst, fn): def group_by(lst, fn):
groups = {} return {key : [el for el in lst if fn(el) == key] for key in map(fn,lst)}
for key in list(map(fn,lst)):
groups[key] = [item for item in lst if fn(item) == key]
return groups
``` ```
```py ```py
import math import math
group_by([6.1, 4.2, 6.3], math.floor); # {4: [4.2], 6: [6.1, 6.3]} group_by([6.1, 4.2, 6.3], math.floor) # {4: [4.2], 6: [6.1, 6.3]}
group_by(['one', 'two', 'three'], len); # {3: ['one', 'two'], 5: ['three']} group_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']}
``` ```