The three pieces of code I’ve read here are designed to determine whether the elements in the list all meet a given condition. Determine whether there are elements in the list that meet the given conditions; And to determine if none of the elements in the list fit a given condition.
The code snippet read here is from 30-seconds-of-Python.
every
def every(lst, fn=lambda x: x) :
return all(map(fn, lst))
# EXAMPLES
every([4.2.3].lambda x: x > 1) # True
every([1.2.3]) # True
Copy the code
Every is used to determine whether the elements in the list LST conform to the given criterion fn.
The code first uses map to return an iterator that applies the fn criterion to all list elements. We then use the all function to determine whether all the elements in the iterator are True.
All (iterable) receives an iterable and returns True if all elements in the object are True. Note that True is also returned when the object is empty. This function is equivalent to:
def all(可迭代) :
for element in iterable:
if not element:
return False
return True
Copy the code
some
def some(lst, fn=lambda x: x) :
return any(map(fn, lst))
# EXAMPLES
some([0.1.2.0].lambda x: x >= 2 ) # True
some([0.0.1.0]) # True
Copy the code
Some is used to determine whether there are elements in the LST list that meet the given condition FN.
The code first uses map to return an iterator that applies the fn criterion to all list elements. We then use the any function to determine whether at least one element in the iterator is True.
Any (iterable) receives an iterable and returns True if any of the elements in the object are True. Note that False is returned when the object is empty. This function is equivalent to:
def any(可迭代) :
for element in iterable:
if element:
return True
return False
Copy the code
none
def none(lst, fn=lambda x: x) :
return all(not fn(x) for x in lst)
# EXAMPLES
none([0.1.2.0].lambda x: x >= 2 ) # False
none([0.0.0]) # True
Copy the code
None is used to determine whether the elements in the list LST do not meet the given criteria (FN).
The code starts by using a generator expression to generate a generator that applies the not FN criterion to all list elements. We then use the all function to determine whether all the elements in the iterator are True.
lst = [0.1.2.0]
def fn(x) :
return x >= 2
type(not fn(x) for x in lst) # <class 'generator'>
Copy the code