list, tuple, or string Return those items of sequ_过滤器怎么处理参数">
当前位置:   article > 正文

filter多个参数处理方法+Python的filter过滤器理解_过滤器怎么处理参数

过滤器怎么处理参数

filter()函数分析

1.源码:

  1. def filter(function_or_none, sequence): # known special case of filter
  2. """
  3. filter(function or None, sequence) -> list, tuple, or string
  4. Return those items of sequence for which function(item) is true. If
  5. function is None, return the items that are true. If sequence is a tuple
  6. or string, return the same type, else return a list.
  7. """
  8. pass
 

2.分析:

filter()  函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

3.举例:

  1. def func_filter(x):
  2. if x > 0:
  3. return True
  4. else:
  5. return False
  6. filter(func_filter,[-1,0,1])
  7. filter(func_filter,'abc')
  8. filter(func_filter,(-1,0,1))

结果:

4.如果一个函数需要传入多个参数 并用 filter进行过滤

不能改造filter原的方法,我们可以改变自己的函数传参类型,从而控制函数可以使用filter方法

  1. def func_filter(vals):
  2. if len(vals) == 2 and vals[0] > 0 and vals[1] > 0:
  3. return True
  4. else:
  5. return False
  6. filter(func_filter,[[-1,-1],[0,0],[1,1]])
  7. filter(func_filter,'abc')
  8. filter(func_filter,((-1,-1),(0,0),(1,1)))
结果:

 
以上.
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/355549
推荐阅读
相关标签
  

闽ICP备14008679号