Last active
July 20, 2023 02:49
-
-
Save kenchou/2221e83a4f5acfa6df5a61a5ea5c3c39 to your computer and use it in GitHub Desktop.
deduplicate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def deduplicate(ls: list, selector=lambda x: x) -> list: | |
seen = set() | |
return [x for x in ls if (e := selector(x)) not in seen and (seen.add(e) or True)] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def test_deduplicate(): | |
# 普通 list 去重 | |
assert deduplicate([1, 2, 2, 3]) == [1, 2, 3] | |
data = [{"id": 1, "name": "a"}, {"id": 1, "name": "b"}] | |
# 整个 dict 比较 | |
assert deduplicate(data, lambda x: tuple(x.items())) == data | |
# 某个 key 作为唯一键比较 | |
assert deduplicate(data, lambda x: x["id"]) == [{"id": 1, "name": "a"}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment