zoukankan      html  css  js  c++  java
  • 为什么 “return s and s.strip()” 在用 filter 去掉空白字符时好使?

    如题:

    给定一个数组,其中该数组中的每个元素都为字符串,删除该数组中的空白字符串。

    _list = ["A", "", "", "B", "", "C", "", "", "D", "", ' ']

    根据廖大文章,答案是这样的:
    def not_empty(s):
        return s and s.strip()
    
    print(list(filter(not_empty, _list)))
    
    

    结果:

    ['A', 'B', 'C']

     

    Why does “return s and s.strip()” work when using filter?

     

    用filter()来过滤元素,如果s是None,s.strip()会报错,但s and s.strip()不会报错

    >>> _list = ["A", "", "", "B", "", "C", "", "", "D", "", ' ',None]
    >>> def not_empty(s):
    ... return s and s.strip()
    ...
    >>> print(list(filter(not_empty, _list)))
    ['A', 'B', 'C', 'D']


    >>> def not_empty(s):
    ... return s.strip()
    ...
    >>> print(list(filter(not_empty, _list)))
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 2, in not_empty
    AttributeError: 'NoneType' object has no attribute 'strip'

     

    涉及的知识点:

    1. filter原理:

    filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象。

    此函数接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数

    然后返回 True 或 False,最后将返回 True 的元素放到新列表中。 格式:filter(function, iterable)

    2. python的and 返回值

    >>> 'a' and 'b'
    'b'
    >>> '' and 'b'
    ''
    >>> 'b' and ''
    ''
    >>> 'a' and 'b' and 'c'
    'c'
    >>> '' and None and 'c'
    ''

    在布尔上下文中从左到右演算表达式的值,如果布尔上下文中的所有值都为真,那么 and 返回最后一个值。

    如果布尔上下文中的某个值为假,则 and 返回第一个假值

    3. strip()方法作用

    去掉字符串前、后空白字符 (即空格)

    >>> print("     j d s fk     ".strip())
    j d s fk


  • 相关阅读:
    MYSQL删除表的记录后如何使ID从1开始
    Python chardet 字符编码判断
    中文搜索引擎技术揭密
    python 处理中文网页时,忽略特殊字符,忽略异常
    cmd 之基础命令
    自己写的删除主键的存储过程
    朝花夕拾delphi的三层结构
    ERWIN中的一对多标识关系和一对多非标识关系
    翻页用的SQL
    关于 Ajax 的一篇通俗易懂的文章
  • 原文地址:https://www.cnblogs.com/liangmingshen/p/9992845.html
Copyright © 2011-2022 走看看