如何在列表理解中设置局部变量? [英] How to set local variable in list comprehension?

查看:66
本文介绍了如何在列表理解中设置局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,它接受一个列表并返回一个对象:

I have a method that takes a list and returns an object:

# input a list, returns an object
def map_to_obj(lst):
    a_list = f(lst)
    return a_list[0] if a_list else None

我想获取一个包含所有不是None的映射元素的列表.

I want to get a list that contains all the mapped elements that aren't None.

赞:

v_list = [v1, v2, v3, v4]

[map_to_obj(v) for v in v_list if map_to_obj(v)]

但是在列表理解中两次调用map_to_obj方法似乎并不好.

But it doesn't seem good to call the map_to_obj method twice in the list comprehension.

是否有一种方法可以在列表推导中包含局部变量,从而使其具有更好的性能?

Is there a way to have local variables in list comprehensions so that it can have better performance?

还是编译器会自动对其进行优化?

Or does the compiler optimize it automatically?

这就是我想要的:

(sml like)
[let mapped = map_to_obj(v) in for v in v_list if mapped end] 

推荐答案

Python 3.8开始,并引入赋值表达式(PEP 572)(:=运算符),可以在列表推导中使用局部变量,以避免调用同一函数两次:

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's possible to use a local variable within a list comprehension in order to avoid calling twice the same function:

在我们的例子中,我们可以将map_to_obj(v)的求值命名为变量o,同时使用表达式的结果来过滤列表.因此使用o作为映射值:

In our case, we can name the evaluation of map_to_obj(v) as a variable o while using the result of the expression to filter the list; and thus use o as the mapped value:

[o for v in [v1, v2, v3, v4] if (o := map_to_obj(v))]

这篇关于如何在列表理解中设置局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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