首页 > 解决方案 > 用于函数式编程的 Pythonic 风格

问题描述

我对 Python 没有太多经验。我正在尝试以我习惯于使用 Java 和 JavaScript 的功能风格进行编码,例如

var result = getHeroes('Jedi')
  .map(hero => { hero: hero, movies: getMovies(hero) })
  .filter(x => x.movies.contains('A New Hope'));

我正在尝试在 Python 中做类似的事情,但我无法获得相同的链接样式。我不得不把它分解成两个我不喜欢的陈述:

tmp = ((hero, get_movies(hero)) for hero in get_heroes('jedi'))
result = ((hero, movies) for (hero, movies) in tmp if movies.contains('A New Hope')

我有两个问题:

  1. Python中有没有办法接近第一种风格?
  2. 在 Python 中这样做的惯用方式是什么?

谢谢你。

标签: pythonfunctional-programming

解决方案


作为一个热爱函数式编程的人,不要在 Python 中写函数式风格

这条硬性规定有点笨拙,当然有一些方法可以使用典型的函数式工具来做你想做的事情,比如map,filterreducefunctools.reduce在 Python 中调用),但是你的函数式代码可能看起来更丑陋比罪,在这种情况下,没有理由更喜欢它而不是一些命令和漂亮的东西。

result = []
for hero in get_heros("Jedi"):
    movies = get_movies(hero)
    for movie in movies:
        if "A New Hope" in movies:
            result.append((hero, movies))

这可以通过列表理解来完成,但可能不太可读。

result = [(hero, movies) for hero in get_heros("Jedi")
          for movies in [get_movies(hero)] if "A New Hope" in movies]

推荐阅读