将列表推导用于副作用是 Pythonic 吗?

Is it Pythonic to use list comprehensions for just side effects?(将列表推导用于副作用是 Pythonic 吗?)

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

问题描述

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

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

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

Note that I don't save the list anywhere

Or should I call this func like this:

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

Which is better and why?

解决方案

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 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将列表推导用于副作用是 Pythonic 吗?

基础教程推荐