python - python中的清洁操作管道
问题描述
我有一个很长的管道,它对字符串列表进行各种操作input_list
。管道将每个单词映射为小写,替换下划线,过滤掉特定单词,删除重复项,并剪辑到一定长度。
result = list(set(filter(lambda x : x != word, map(lambda x : x.lower().replace('_',' '), input_list))))[:clip_length]
我的问题是它的可读性不是很好:它不是很清楚这个管道的输入是什么以及应用操作的顺序。看着有点痛,除非它得到很好的评论,否则我可能不知道它以后会做什么。
有什么方法可以在 python 中编写一个管道,我可以清楚地看到哪些操作以什么顺序发生,什么进出什么?更具体地说,我希望能够编写它以便操作从右到左或从左到右,而不是从内到外。
解决方案
那是函数式,您可以从最里面的表达式向最外面的表达式阅读。
将其放在多行并带有一些注释可以提高可读性:
result = list( # (5) convert to list
set( # (4) convert to set (remove dupes)
filter(
lambda x: x != word, # (3) filter items != to word
map(
lambda x: x.lower().replace('_',' '), # (2) apply transformation
input_list # (1) take input_list
)
)
)
)[:clip_length] # (6) limit number of results
这是一个品味问题。我倾向于喜欢这样的单个表达式,使用最小的格式可以很好地适应:
result = list(set(filter(lambda x : x != word,
map(lambda x : x.lower().replace('_',' '), input_list))))[:clip_length]
等效的命令式处理是:
result = set()
for x in input_list:
x = x.lower().replace('_', ' ')
if x != word:
result.add(x)
result = list(result)[:clip_length]
推荐阅读
- spring-boot - 如何使用 Spring Boot 使用 RestHighLevelClient 递归地将数据插入到 elasticsearch 中的嵌套文档
- python - Python/Pandas - 时间序列预测:从两个不同的数据帧构建时间数据帧
- oracle-apex - 如何获取复选框组中复选框的显示值?
- java - 如何验证响应并从 Rest Assured 中的响应正文中提取值?
- jquery - 尝试创建一个网页,其中将显示 10 个输入字段(从数据库预填充),如果我编辑其中任何一个,它将更改数据库中的值
- postgresql - 如何在数据集中获取关系(家庭亲属)?
- python - AttributeError:类型对象'h5py.h5.H5PYConfig'没有属性'__reduce_cython__',同时使用Tensorflow对象检测API
- database - 在我的 Visual Studio 2019 中,基于服务的数据库不可用
- python - 通过 Pyinstaller 生成的 Python 到 EXE 不能为基于 kivy 的 python 运行
- python - 使用 selenium 和 chromedriver 无法在 Heroku 上加载 Instagram 登录页面