将列表推导用于副作用是否是 Pythonic? [英] Is it Pythonic to use list comprehensions for just side effects?

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

问题描述

想想我调用的函数是为了它的副作用,而不是返回值(比如打印到屏幕、更新 GUI、打印到文件等).

Think about a function that I'm calling for its 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天全站免登陆