From 8911146de18b19b35c4f1ba9435bcdbc5ddb46de Mon Sep 17 00:00:00 2001 From: Pablo Baeyens Date: Sat, 4 Jan 2020 14:29:42 +0100 Subject: [PATCH] Improve filter functions --- snippets/filter_non_unique.md | 8 ++++++-- snippets/filter_unique.md | 8 ++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/snippets/filter_non_unique.md b/snippets/filter_non_unique.md index b9dd96923..6563285a0 100644 --- a/snippets/filter_non_unique.md +++ b/snippets/filter_non_unique.md @@ -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 diff --git a/snippets/filter_unique.md b/snippets/filter_unique.md index 92184cf0b..7632cd494 100644 --- a/snippets/filter_unique.md +++ b/snippets/filter_unique.md @@ -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