Nik*_*iou 5 python functional-programming
我对 Python 没有太多经验。我正在尝试以函数式风格进行编码,就像我习惯的 Java 和 JavaScript 一样,例如
var result = getHeroes('Jedi')
.map(hero => { hero: hero, movies: getMovies(hero) })
.filter(x => x.movies.contains('A New Hope'));
Run Code Online (Sandbox Code Playgroud)
我正在尝试在 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')
Run Code Online (Sandbox Code Playgroud)
我有两个问题:
谢谢。
作为喜欢函数式编程的人,不要在 Python 中以函数式风格编写。
这个严格而快速的规则有点笨手笨脚,当然有一些方法可以使用典型的函数工具(如map、filter和reduce(在 Python 中调用functools.reduce))来完成您想要做的事情,但您的函数代码可能看起来会更难看比罪恶更重要,在这种情况下,没有理由更喜欢它而不是命令性的和美丽的东西。
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))
Run Code Online (Sandbox Code Playgroud)
这可以通过列表理解来完成,但可能可读性较差。
result = [(hero, movies) for hero in get_heros("Jedi")
for movies in [get_movies(hero)] if "A New Hope" in movies]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
403 次 |
| 最近记录: |