zoukankan      html  css  js  c++  java
  • 干货来袭,收藏方便找到该网站

    def not_empty(s):
    return s and s.strip()
    print(list(filter(not_empty, ['A', '', 'B', None,'C', ' '])))
     
      代码很简洁,效果嘛,可以丢到 Python在线工具|菜鸟教程 跑跑看,很 nice ~ 但是函数 not_empty 的返回值有点复杂,可以仔细分析一下:
    • - 假设字符串a和b作and运算 a and b:
    • - 若两者均为非空,则 a and b = b;
    • - 若两者均非None,且至少一个为空,即 '',则 a and b = ''
    • - 若至少一个等于None,则 a and b = None
      由于 strip() 函数本身是针对 str 类型进行操作的,所以当 s = None 时,用单独用一句 return s.strip() 会报 “ 'NoneType' object has no attribute 'strip'” 的错误;
      不过如果能保证 s[] 中不包含 None 成员,函数其实也可以直接写成
    def not_empty(s):
    return s.strip()
    print(list(filter(not_empty, ['A', '', 'B', 'C', ' '])))
     
      因此, return s and s.strip() 的作用在于排除 s = None 的情况,而不是排除 s = '' 或者 s = '  ' 的情况。
      但是为什么当 s = None 时,return s and s.strip()不会报错呢? 原因是当参与 and 运算的参数从前至后一旦出现一个不可能使得 and 为 True 的情况时,那么 and 运算就提前终止,又因为python本身是解释性语言,一边运行一边检查,还没有运行到 s and s.strip() 中的 s.strip() 时就已经运行完成这一句了(虚晃一枪),自然就不会报错了~
      最后用 lambda 表达式可以对上述程序作进一步封装:
    def str_Nempty(s):
    return list(filter(lambda s: s and s.strip(),s))
    print(str_Nempty(['A', '', 'B', 'C', ' ']))
     
    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

    有相同爱好的可以进来一起讨论哦:企鹅群号:1046795523

    学习视频资料:http://www.makeru.com.cn/live/1392_1164.html?s=143793

  • 相关阅读:
    lhgdialogv3.13 使用点滴
    CheckBoxList 取值 及选中相关用法
    repeater 及 gridview 中绑定短日期
    数据库中日期大小的判断
    父子不同窗口间刷新传值
    子级Repeater获取父级Repeater绑定项的值
    vs.net 2010 web 项目中使用 webservice
    web打印实现方案 Lodop6.034 使用方法总结
    用 showModalDialog 方法回传数据到父页中去
    vs.net2010中使用 Ajax Control Toolkit
  • 原文地址:https://www.cnblogs.com/jinwenyi/p/13554069.html
Copyright © 2011-2022 走看看