在Python列表推导中缓存值 [英] Caching values in Python list comprehensions

查看:26
本文介绍了在Python列表推导中缓存值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下列表理解:

I'm using the following list comprehension:

resources = [obj.get("file") for obj in iterator if obj.get("file") != None]

在if语句中检查它时,是否有一种方法可以缓存" obj.get("file")的值,从而不必调用 get 再次在obj上生成返回列表时?

Is there a way to "cache" the value of obj.get("file") when it's checked in the if statement so that it doesn't have to call get again on obj when it generates the return list?

推荐答案

如果您希望使用列表/迭代器理解而不是使用 filter ,则可以简单地使用:

If you want to stay with list / iterator comprehensions instead of using filter you can simply use:

resources = [file_obj
             for file_obj in (obj.get("file") for obj in iterator)
             if file_obj is not None]

这篇关于在Python列表推导中缓存值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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