python -- 优雅地删除字符列表中的空字符及None元素

  这段代码其实是在 “廖雪峰官方网站” 里的对于 python 中 高阶函数 filter 的使用 中看到的,当时学的时候在这个地方思考了蛮久,觉得很有意思,就进行了一点整理。

  文中给出了这样的一段删除空字符串的代码:

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', '  ']))

  刺激!😲

posted @ 2020-06-22 11:59  贝_塔  阅读(1951)  评论(1编辑  收藏  举报