add uniq to list

This commit is contained in:
Prodesire 2017-11-21 13:10:44 +08:00
parent 4aa8907956
commit eef3a2c79a
2 changed files with 22 additions and 0 deletions

17
pydu/list.py Normal file
View File

@ -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

5
tests/test_list.py Normal file
View File

@ -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]