Improve filter functions

This commit is contained in:
Pablo Baeyens
2020-01-04 14:29:42 +01:00
parent 2ba974cd2d
commit 8911146de1
2 changed files with 12 additions and 4 deletions

View File

@ -5,11 +5,15 @@ tags: list,beginner
Filters out the non-unique values in a list.
Use list comprehension and `list.count()` to create a list containing only the unique values.
Use `Counter` to get the count of each value in the list.
Use list comprehension to create a list containing only the unique values.
```py
from collections import Counter
def filter_non_unique(lst):
return [item for item in lst if lst.count(item) == 1]
counter = Counter(lst)
return [item for item, count in counter.items() if count == 1]
```
```py

View File

@ -5,11 +5,15 @@ tags: list,beginner
Filters out the unique values in a list.
Use list comprehension and `list.count()` to create a list containing only the non-unique values.
Use `Counter` to get the count of each value in the list.
Use list comprehension to create a list containing only the non-unique values.
```py
from collections import Counter
def filter_unique(lst):
return [x for x in set(item for item in lst if lst.count(item) > 1)]
counter = Counter(lst)
return [item for item, count in counter.items() if count > 1]
```
```py