diff options
author | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2024-06-01 17:06:18 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-06-01 17:06:18 (GMT) |
commit | 60393f5f14c7741930de73c46475c9b5c1809dc3 (patch) | |
tree | cc47c7033bb1abfd8eddef55809e3fc03e17fc98 | |
parent | 55f65156cb0b21a7238d3eda169473daba9f5024 (diff) | |
download | cpython-60393f5f14c7741930de73c46475c9b5c1809dc3.zip cpython-60393f5f14c7741930de73c46475c9b5c1809dc3.tar.gz cpython-60393f5f14c7741930de73c46475c9b5c1809dc3.tar.bz2 |
[3.12] Add unique() recipe to itertools docs (gh-119911) (gh-119917)
-rw-r--r-- | Doc/library/itertools.rst | 16 |
1 files changed, 14 insertions, 2 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 057b9cc..21bb3f1 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -849,7 +849,7 @@ and :term:`generators <generator>` which incur interpreter overhead. return len(take(2, groupby(iterable, key))) <= 1 def unique_justseen(iterable, key=None): - "List unique elements, preserving order. Remember only the element just seen." + "Yield unique elements, preserving order. Remember only the element just seen." # unique_justseen('AAAABBBCCDAABBB') → A B C D A B # unique_justseen('ABBcCAD', str.casefold) → A B c A D if key is None: @@ -857,7 +857,7 @@ and :term:`generators <generator>` which incur interpreter overhead. return map(next, map(operator.itemgetter(1), groupby(iterable, key))) def unique_everseen(iterable, key=None): - "List unique elements, preserving order. Remember all elements ever seen." + "Yield unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') → A B C D # unique_everseen('ABBcCAD', str.casefold) → A B c D seen = set() @@ -872,6 +872,11 @@ and :term:`generators <generator>` which incur interpreter overhead. seen.add(k) yield element + def unique(iterable, key=None, reverse=False): + "Yield unique elements in sorted order. Supports unhashable inputs." + # unique([[1, 2], [3, 4], [1, 2]]) → [1, 2] [3, 4] + return unique_justseen(sorted(iterable, key=key, reverse=reverse), key=key) + def sliding_window(iterable, n): "Collect data into overlapping fixed-length chunks or blocks." # sliding_window('ABCDEFG', 4) → ABCD BCDE CDEF DEFG @@ -1593,6 +1598,13 @@ The following recipes have a more mathematical flavor: >>> ''.join(input_iterator) 'AAABBBCCDAABBB' + >>> list(unique([[1, 2], [3, 4], [1, 2]])) + [[1, 2], [3, 4]] + >>> list(unique('ABBcCAD', str.casefold)) + ['A', 'B', 'c', 'D'] + >>> list(unique('ABBcCAD', str.casefold, reverse=True)) + ['D', 'c', 'B', 'A'] + >>> d = dict(a=1, b=2, c=3) >>> it = iter_except(d.popitem, KeyError) >>> d['d'] = 4 |