From eef3a2c79af2406f5ba444e456364f0fb53be289 Mon Sep 17 00:00:00 2001 From: Prodesire Date: Tue, 21 Nov 2017 13:10:44 +0800 Subject: [PATCH] add uniq to list --- pydu/list.py | 17 +++++++++++++++++ tests/test_list.py | 5 +++++ 2 files changed, 22 insertions(+) create mode 100644 pydu/list.py create mode 100644 tests/test_list.py diff --git a/pydu/list.py b/pydu/list.py new file mode 100644 index 0000000..503bb3a --- /dev/null +++ b/pydu/list.py @@ -0,0 +1,17 @@ +def uniq(seq, key=None): + """ + Removes duplicate elements from a list while preserving the order of the rest. + + The value of the optional `key` parameter should be a function that + takes a single argument and returns a key to test the uniqueness. + """ + key = key or (lambda x: x) + seen = set() + uniq_list = [] + for value in seq: + uniq_value = key(value) + if uniq_value in seen: + continue + seen.add(uniq_value) + uniq_list.append(value) + return uniq_list diff --git a/tests/test_list.py b/tests/test_list.py new file mode 100644 index 0000000..dafba83 --- /dev/null +++ b/tests/test_list.py @@ -0,0 +1,5 @@ +from pydu.list import uniq + + +def test_uniq(): + assert uniq([1, 4, 0, 2, 0, 3]) == [1, 4, 0, 2, 3]