Python Code Reading Logical Judgment of List Elements

  • 2021-12-04 19:11:38
  • OfStack

Directory 1, every 2. some 3. none

1. 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

every Used to judge the list lst Whether all the elements in meet the given judgment condition fn.

The code first returns an iterator using map, which applies the decision condition fn to all list elements. Then use the all function to determine whether all the elements in the iterator are True.

all(iterable) Receives an iterable object, and if all elements in this object are True, the function returns True. Note that True is also returned when the object is empty. This function is equivalent to:


def all(iterable):
  for element in iterable:
    if not element:
      return False
  return True


2. 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

some Used to determine whether there are elements in the list lst that meet the given condition fn.

First used in the code map Returns 1 iterator that applies the decision condition fn to all list elements. Then use the any function to determine whether at least one element in the iterator is True .

any(iterable) Receives an iterable object. If any 1 element in this object is True, the function returns True. Note that False is returned when the object is empty. This function is equivalent to:


def any(iterable):
  for element in iterable:
    if element:
      return True
  return False


3. 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

none It is used for judging whether all the elements in the list lst do not meet the given judgment condition fn.

The code first uses the generator expression to generate a generator, which will judge the condition not fn Applies to all list elements. 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'>

Related articles: