Files
30-seconds-of-code/snippets/group_by.md
Angelos Chalaris cb8bbd9745 Update formatting
Update formatting in every_nth
Update formatting in shuffle
Update formatting in has_duplicates
Update formatting in group_by
Update formatting in sum_by
Update formatting in zip
Update formatting in longest_item
Update formatting in bifurcate_by
Update formatting in difference_by
Update formatting in clamp_number
Update formatting in min_by
Update formatting in max_by
Update formatting in union
Update formatting in n_times_string
Update formatting in check_prop
Update formatting in chunk
Update formatting in transpose
Update formatting in bifurcate
Update formatting in union_by
Update formatting in initialize_list_with_range
Update formatting in most_frequent
2020-01-03 13:06:54 +02:00

21 lines
539 B
Markdown

---
title: group_by
tags: list,object,beginner
---
Groups the elements of a list based on the given function.
Use `map()` and `fn` to map the values of the list to the keys of an object.
Use list comprehension to map each element to the appropriate `key`.
```py
def group_by(lst, fn):
return {key : [el for el in lst if fn(el) == key] for key in map(fn, lst)}
```
```py
from math import floor
group_by([6.1, 4.2, 6.3], floor) # {4: [4.2], 6: [6.1, 6.3]}
group_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']}
```