[3.13] Add unique() recipe to itertools docs (gh-119911) (gh-119916)

This commit is contained in:
Miss Islington (bot) 2024-06-01 19:06:04 +02:00 committed by GitHub
parent 9f9be95d66
commit 99d0f51e61
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 14 additions and 2 deletions

View File

@ -857,7 +857,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:
@ -865,7 +865,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()
@ -880,6 +880,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
@ -1605,6 +1610,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