我有一个hack
在list/dict理解中创建别名。你可以使用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
+1虽然我有关于索引元组疑虑。而且,在某些情况下,函数或生成器函数是最佳选择。 – Apalala 2011-01-30 15:50:37