为啥“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']

用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

 

本文转载自https://www.cnblogs.com/liangmingshen/p/9992845.html

 

``` import re import logging import chardet from openpyxl import Workbook def setup_logging(): logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler("extraction.log"), logging.StreamHandler() ] ) def detect_encoding(file_path): try: with open(file_path, 'rb') as f: rawdata = f.read() result = chardet.detect(rawdata) return result['encoding'] except Exception as e: logging.error(f"检测文件编码出现错误: {e}") return None def read_file(file_path): encoding = detect_encoding(file_path) if not encoding: return [] try: with open(file_path, 'r', encoding=encoding) as file: return file.readlines() except FileNotFoundError: logging.error(f"未找到文件: {file_path}") return [] except Exception as e: logging.error(f"读取文件出现错误: {e}") return [] def extract_directories(lines): workbook = Workbook() sheet = workbook.active sheet.append(["一级目录", "二级目录", "三级目录"]) level1 = None level2 = None for line in lines: line = line.strip() if not line: continue match_level1 = re.match(r'!\[img\]\(旵\)(.*)', line) if match_level1: level1 = match_level1.group(1).strip() level2 = None continue match_level2 = re.match(r'!\[img\]\(目\)(.*)', line) if match_level2: level2 = match_level2.group(1).strip() continue match_level3 = re.match(r'!\[img\]\([^)]+\)(.*)', line) if match_level3 and level1 and level2: level3 = match_level3.group(1).strip() sheet.append([level1, level2, level3]) return workbook def save_workbook(workbook, output_file): try: workbook.save(output_file) logging.info(f"已成功将目录信息保存到 {output_file}") except Exception as e: logging.error(f"保存文件出现错误: {e}") def main(): setup_logging() file_path = input("请输入文档文件的路径:") lines = read_file(file_path) if lines: workbook = extract_directories(lines) save_workbook(workbook, "C:/Users/Linboyan/Desktop/123123.log.xlsx") if __name__ == "__main__": main()```优化代码
03-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值