作为喜欢函数式编程的人,不要在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))
这可以通过列表理解来完成,但可能性较差.
result = [(hero, movies) for hero in get_heros("Jedi")
for movies in [get_movies(hero)] if "A New Hope" in movies]