Last active
August 29, 2015 14:22
-
-
Save RobertKolner/afe943e6b1392379d7ec to your computer and use it in GitHub Desktop.
Remove duplicates from list
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
from types import GeneratorType | |
def remove_duplicates(iterable, key=None): | |
iterable_class = type(iterable) | |
if iterable_class in [dict, set]: | |
raise TypeError("You can't remove duplicates from a {}!".format(iterable_class)) | |
if not key: | |
_key = lambda a: a | |
elif not callable(key): | |
_key = lambda a: a[key] | |
else: | |
_key = key | |
s = set() | |
gen = (s.add(_key(i)) or i for i in iterable if _key(i) not in s) | |
if iterable_class == str: | |
return ''.join(gen) | |
elif iterable_class == GeneratorType: | |
return list(gen) | |
return iterable_class(gen) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment