mirror of
https://github.com/python/cpython.git
synced 2024-11-23 18:04:37 +08:00
Improve all_equal() recipe (gh-116081)
Replace conjuction of next() calls with simpler len()/take() logic. Add key function.
This commit is contained in:
parent
81c79961d2
commit
67c19e57b5
@ -863,10 +863,9 @@ which incur interpreter overhead.
|
||||
"Given a predicate that returns True or False, count the True results."
|
||||
return sum(map(pred, iterable))
|
||||
|
||||
def all_equal(iterable):
|
||||
def all_equal(iterable, key=None):
|
||||
"Returns True if all the elements are equal to each other."
|
||||
g = groupby(iterable)
|
||||
return next(g, True) and not next(g, False)
|
||||
return len(take(2, groupby(iterable, key))) <= 1
|
||||
|
||||
def first_true(iterable, default=False, pred=None):
|
||||
"""Returns the first true value in the iterable.
|
||||
@ -1225,6 +1224,8 @@ The following recipes have a more mathematical flavor:
|
||||
|
||||
>>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
|
||||
[True, True, True, False, False]
|
||||
>>> [all_equal(s, key=str.casefold) for s in ('', 'A', 'AaAa', 'AAAB', 'AAABA')]
|
||||
[True, True, True, False, False]
|
||||
|
||||
>>> quantify(range(99), lambda x: x%2==0)
|
||||
50
|
||||
|
Loading…
Reference in New Issue
Block a user