避免在列表理解中两次计算相同的表达式 [英] Avoid computing the same expression twice in list comprehension

查看:82
本文介绍了避免在列表理解中两次计算相同的表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在列表理解中使用一个函数和一个if函数:

I am using a function in a list comprehension and an if function:

new_list = [f(x) for x in old_list if f(x) !=0]

我很烦恼f(x)表达式在每个循环中被计算两次.

It annoys me that the expression f(x) is computed twice in each loop.

有没有一种更清洁的方式来做到这一点?类似于存储值或在列表理解的开始处包含if语句.

Is there a way to do it in a cleaner way? Something along the lines of storing the value or including the if statement at the beginning of the list comprehension.

推荐答案

事先计算结果并对其进行迭代

Compute the results beforehand and iterate over them

new_list = [x for x in map(f, old_list) if x !=0]

此外,由于map会在访问元素时计算每个元素的结果,因此这仅仅是一个循环.

Moreover, since map computes the result per element when the element is accessed this is just one loop.

这篇关于避免在列表理解中两次计算相同的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆