13916729435 发表于 2018-8-15 10:18:04

python内置函数5-filter()

  Help on built-in function filter in module __builtin__:
  filter(...)
  filter(function or None, sequence) -> list, tuple, or string
  Return those items of sequence for which function(item) is true.If
  function is None, return the items that are true.If sequence is a tuple
  or string, return the same type, else return a list.
  filter(function, iterable)

  Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the>  Note that filter(function, iterable) is equivalent to if function is not None and if function is None.
  See itertools.ifilter() and itertools.ifilterfalse() for iterator versions of this function, including a variation that filters for elements where the function returns false.
  中文说明:
  该函数的目的是提取出seq中能使func为true的元素序列。func函数是一个布尔函数,filter()函数调用这个函数一次作用于seq中的每一个元素,筛选出符合条件的元素,并以列表的形式返回。
  >>> nums=
  >>> def nums_res(x):
  ...   return x%2 == 0 and x%3 == 0
  ...
  >>> print filter(nums_res,nums)
  
  >>> def is_odd(n):
  ...   return n%2==1
  ...
  >>> filter(is_odd, )
  
  >>> def not_empty(s):
  ...   return s and s.strip()
  ...
  >>> filter(not_empty, ['A','','B',None,'C',''])
  ['A', 'B', 'C']
页: [1]
查看完整版本: python内置函数5-filter()