zoukankan      html  css  js  c++  java
  • day11 filter函数

    场景模拟:我想判断某个列表里面的某个元素怎么怎么样
    基础方法,如果需要判断多次则重复代码
    1 ret = []
    2 move_peole = ["alex","sb_wupeiqi","yangtuo","sb_yuanhao"]
    3 for p in move_peole:
    4     if    not p.startswith("sb"):
    5         ret.append(p)
    6 
    7 print(ret)
    函数方法
    利用参数更换来多次代入执行,判断方式单一
     1 move_peole = ["alex","sb_wupeiqi","yangtuo","sb_yuanhao"]
     2 move_peole1 = ["alex","wupeiqi_sb","yangtuo","yuanhao_sb"]
     3 def    filter_test(array):
     4     ret = []
     5     for p in array:
     6         if not p.startswith("sb"):
     7             ret.append(p)
     8     return ret
     9 
    10 print(filter_test(move_peole))
    双函数参数调用
    解决了方法限定的问题但是代码复杂,代码量大
     1 move_peole1 = ["alex","wupeiqi_sb","yangtuo","yuanhao_sb"]
     2 def sb_show(n):
     3     return n.endswith("sb")
     4 def    filter_test(funk,array):
     5     ret = []
     6     for p in array:
     7         if not funk(p):
     8             ret.append(p)
     9     return ret
    10 
    11 print(filter_test(sb_show,move_peole1))
    终极版本目前可以做到的最好的版本
     1 def sb_show(n):
     2     return n.endswith("sb")
     3 move_peole1 = ["alex","wupeiqi_sb","yangtuo","yuanhao_sb"]
     4 lambda x:x.endswith("sb")
     5 def    filter_test(funk,array):
     6     ret = []
     7     for p in array:
     8         if not funk(p):
     9             ret.append(p)
    10     return ret
    11 print(filter_test(lambda x:x.endswith("sb"),move_peole1))
    filter 函数,计算布尔值,得出为true则保留
    利用filter可以实现的效果
    格式:filter(方法,参数)
    1 move_peole1 = ["alex","wupeiqi_sb","yangtuo","yuanhao_sb"]
    2 print(filter (lambda x:not x.endswith("sb"),move_peole1))
    3 print(list(filter (lambda x:not x.endswith("sb"),move_peole1)))









  • 相关阅读:
    jq隐藏页面的一行(循环隐藏10行)
    Button的OnClientClick()事件不起作用?
    Infopath自定义表单实现列表字段联动
    SharePoint 2013的传出电子邮件设置
    codeforces Looksery Cup 2015 D. Haar Features
    codeforces Looksery Cup 2015 H Degenerate Matrix
    poj3321 Apple Tree
    poj1990 MooFest
    poj2155 Matrix
    hdu1556 Color the ball
  • 原文地址:https://www.cnblogs.com/shijieli/p/9689799.html
Copyright © 2011-2022 走看看