python - 用于函数式编程的 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')
我有两个问题:
- Python中有没有办法接近第一种风格?
- 在 Python 中这样做的惯用方式是什么?
谢谢你。
解决方案
作为一个热爱函数式编程的人,不要在 Python 中写函数式风格。
这条硬性规定有点笨拙,当然有一些方法可以使用典型的函数式工具来做你想做的事情,比如map
,filter
和reduce
(functools.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]
推荐阅读
- flutter - 是否可以在 NotificationListener 中检测 ScrollNotification 的来源
- angular - Angular 多个 .subscribe 用于
- assets - zipline:如何找到符号的 sid,例如“AAPL”
- c# - 使用 dot.net 客户端 SolaceSystems.Solclient.Messaging 缺少 libcrypto-1_1-x64.dll
- c# - 在同步代码中等待输入而不阻塞的最佳方法
- ruby - 红宝石:在heroku上使用credentials.yml.enc?
- mongodb - 查询 MongoDb 聚合连接两个集合
- laravel - Laravel - 在单个请求中处理大量小数据条目,总执行时间超过 2 分钟
- python - 使用 Geany IDE (Raspberry Pi Raspbian) 执行 .py 文件时出现权限被拒绝错误
- azure-eventhub - 如何禁用 eventHubs 命名空间?