Imrove frequencies snippet implementation (#234)
Co-authored-by: Isabelle Viktoria Maciohsek <maciv@hotmail.gr>
This commit is contained in:
@ -5,16 +5,12 @@ tags: list,intermediate
|
|||||||
|
|
||||||
Returns a dictionary with the unique values of a list as keys and their frequencies as the values.
|
Returns a dictionary with the unique values of a list as keys and their frequencies as the values.
|
||||||
|
|
||||||
- Use a `for` loop to populate a dictionary, `f`, with the unique values in `lst` as keys, adding to existing keys every time the same value is encountered.
|
- Use `list.count()` to get the frequency of each unique element.
|
||||||
|
- Use `dict()` constructor to return a dictionary with the unique elements of the list as keys and their frequencies as the values.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
from functools import reduce
|
|
||||||
|
|
||||||
def frequencies(lst):
|
def frequencies(lst):
|
||||||
f = {}
|
return dict((k, lst.count(k)) for k in lst)
|
||||||
for x in lst:
|
|
||||||
f[x] = f[x] + 1 if x in f else 1
|
|
||||||
return f
|
|
||||||
```
|
```
|
||||||
|
|
||||||
```py
|
```py
|
||||||
|
|||||||
Reference in New Issue
Block a user