snippetpythonTip
Filter unique list values
Viewed 0 times
filteruniquepythonlistvalues
Problem
Using
Similarly, you can create a list with the non-unique values filtered out. All you need to do is to change the condition in the list comprehension.
collections.Counter, you can get the count of each value in the list. Then, you can use a list comprehension to filter out the unique values from a list.Similarly, you can create a list with the non-unique values filtered out. All you need to do is to change the condition in the list comprehension.
Solution
from collections import Counter
def filter_unique(lst):
return [item for item, count in Counter(lst).items() if count > 1]
filter_unique([1, 2, 2, 3, 4, 4, 5]) # [2, 4]Code Snippets
from collections import Counter
def filter_unique(lst):
return [item for item, count in Counter(lst).items() if count > 1]
filter_unique([1, 2, 2, 3, 4, 4, 5]) # [2, 4]from collections import Counter
def filter_non_unique(lst):
return [item for item, count in Counter(lst).items() if count == 1]
filter_non_unique([1, 2, 2, 3, 4, 4, 5]) # [1, 3, 5]Context
From 30-seconds-of-code: filter-unique
Revisions (0)
No revisions yet.