使用列表推导只是副作用是Pythonic吗? [英] Is it Pythonic to use list comprehensions for just side effects?

查看:53
本文介绍了使用列表推导只是副作用是Pythonic吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我要调用的函数的副作用,而不是返回值(例如打印到屏幕,更新GUI,打印到文件等).

Think about a function that I'm calling for it's side effects, not return values (like printing to screen, updating GUI, printing to a file, etc.).

def fun_with_side_effects(x):
    ...side effects...
    return y

现在,使用列表推导功能来调用此函数是 Pythonic 吗?

Now, is it Pythonic to use list comprehensions to call this func:

[fun_with_side_effects(x) for x in y if (...conditions...)]

请注意,我不会将列表保存在任何地方

或者我应该这样称呼这个函数吗?

Or should I call this func like this:

for x in y:
    if (...conditions...):
        fun_with_side_effects(x)

哪个更好,为什么?

推荐答案

这样做是非常反Python的,任何经验丰富的Pythonista都会为您带来麻烦.中间列表在创建之后就被丢弃了,它可能非常大,因此创建起来很昂贵.

It is very anti-Pythonic to do so, and any seasoned Pythonista will give you hell over it. The intermediate list is thrown away after it is created, and it could potentially be very, very large, and therefore expensive to create.

这篇关于使用列表推导只是副作用是Pythonic吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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