首页 > 解决方案 > python中的清洁操作管道

问题描述

我有一个很长的管道,它对字符串列表进行各种操作input_list。管道将每个单词映射为小写,替换下划线,过滤掉特定单词,删除重复项,并剪辑到一定长度。

result = list(set(filter(lambda x : x != word, map(lambda x : x.lower().replace('_',' '), input_list))))[:clip_length]

我的问题是它的可读性不是很好:它不是很清楚这个管道的输入是什么以及应用操作的顺序。看着有点痛,除非它得到很好的评论,否则我可能不知道它以后会做什么。

有什么方法可以在 python 中编写一个管道,我可以清楚地看到哪些操作以什么顺序发生,什么进出什么?更具体地说,我希望能够编写它以便操作从右到左或从左到右,而不是从内到外。

标签: pythonfunctional-programmingpipeline

解决方案


那是函数式,您可以从最里面的表达式向最外面的表达式阅读。

将其放在多行并带有一些注释可以提高可读性:

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]

推荐阅读