更新: Python 3.8中引入了海象操作符:=,它既赋值给变量,同时也将被赋的值作为结果返回。根据@MartijnVanAttekum的回答,我建议在项目中使用它之前等待一年左右,因为Python 3.6和3.7仍然很流行,但它比我下面提出的别名建议更好。
我有一个hack可以在列表/字典推导式中创建别名。你可以使用for alias_name in [alias_value]的技巧。例如,您有这个昂贵的函数:
def expensive_function(x):
print("called the very expensive function, that will be $2")
return x*x + x
还有一些数据:
data = [4, 7, 3, 7, 2, 3, 4, 7, 3, 1, 1 ,1]
接下来,您想对每个元素应用昂贵的函数,并基于它进行过滤。您需要执行以下操作:
result = [
(x, expensive)
for x in data
for expensive in [expensive_function(x)] #alias
if expensive > 3
]
print(result)
第二个for循环只会遍历长度为1的列表,实际上将其变成了一个别名。输出结果将显示昂贵的函数被调用了12次,每个数据元素恰好一次。尽管如此,函数的结果被使用的次数最多是两次,一次用于过滤器,一次可能用于输出。
请始终确保像我这样使用多行来布置这样的推导式,并在别名所在的行后附加#alias。如果您使用别名,则推导式会变得非常复杂,您应该帮助未来的代码读者理解您正在做什么。这不是 Perl,你知道的;)
为了完整起见,输出:
called the very expensive function, that will be $2
called the very expensive function, that will be $2
called the very expensive function, that will be $2
called the very expensive function, that will be $2
called the very expensive function, that will be $2
called the very expensive function, that will be $2
called the very expensive function, that will be $2
called the very expensive function, that will be $2
called the very expensive function, that will be $2
called the very expensive function, that will be $2
called the very expensive function, that will be $2
called the very expensive function, that will be $2
[(4, 20), (7, 56), (3, 12), (7, 56), (2, 6), (3, 12), (4, 20), (7, 56), (3, 12)]
代码:http://ideone.com/7mUQUt
for (x, f(x)) in ((x, f(x)) for x in bigList) if f(x) < p。 - Ramin Melikov