我发现自己经常想写这样的Python列表理解:
nearbyPoints = [(n, delta(n,x)) for n in allPoints if delta(n,x)<=radius]
希望这能为我为什么要这么做提供一些背景,但是 也是需要根据计算/比较多个值的情况 要素:
^{pr2}$所以我有两个问题:
newList = [(x,a=f(x),b=g(a)) for x in bigList if a<p and b<q]
但那不管用。有没有理由不支持这种语法?可以 它是通过this这样的方式完成的? 还是只能使用多个listcomps或for循环?在
随着列表理解变得越来越复杂,它们也开始变得很难阅读。在这种情况下,最好将它们的内部结构转换为生成器函数,并给它们一个(希望)有意义的名称。在
我有一个
hack
在list/dict理解中创建别名。您可以使用for alias_name in [alias_value]
技巧。例如,您有一个昂贵的函数:还有一些数据:
^{pr2}$然后你要对每个元素应用昂贵的函数,并基于它进行过滤。你要做的是:
第二个for将只迭代大小为1的列表,使其成为别名。输出将显示这个昂贵的函数被调用了12次,每个数据元素只调用一次。然而,函数的结果被使用(最多)两次,一次用于滤波器,一次用于输出。在
请始终确保像我一样使用多行来布局这样的理解,并将#alias附加到别名所在的行。如果您使用别名,理解get相当复杂,您应该帮助未来的代码读者了解您正在做什么。这不是perl,你知道;)。在
为了完整性,输出:
代码:http://ideone.com/7mUQUt
关于#1,是的,他们将被评估多次。在
对于#2,其方法是在单独的理解中计算和过滤:
浓缩版:
扩展的较长版本使其更易于遵循:
^{pr2}$这将尽可能少地调用},并且对于
f
和g
(每个f(x)
的值不是< p
将永远不会调用{bigList
中的每个值,f
只调用一次)。在如果您愿意,也可以使用中间变量获得更简洁的代码:
a
和b
使用生成器表达式,这样它们就不必实际实例化列表,并在必要时进行简单的求值。在相关问题 更多 >
编程相关推荐