1from itertools import filterfalse 2 3 4def unique_everseen(iterable, key=None): 5 "List unique elements, preserving order. Remember all elements ever seen." 6 # unique_everseen('AAAABBBCCDAABBB') --> A B C D 7 # unique_everseen('ABBCcAD', str.lower) --> A B C D 8 seen = set() 9 seen_add = seen.add 10 if key is None: 11 for element in filterfalse(seen.__contains__, iterable): 12 seen_add(element) 13 yield element 14 else: 15 for element in iterable: 16 k = key(element) 17 if k not in seen: 18 seen_add(k) 19 yield element 20