相关疑难解决方法(0)

使用列表推导仅仅是副作用是Pythonic吗?

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

def fun_with_side_effects(x):
    ...side effects...
    return y
Run Code Online (Sandbox Code Playgroud)

现在,是Pythonic使用列表推导来调用这个函数:

[fun_with_side_effects(x) for x in y if (...conditions...)]
Run Code Online (Sandbox Code Playgroud)

请注意,我不会将列表保存在任何位置

或者我应该像这样调用这个函数:

for x in y:
    if (...conditions...):
        fun_with_side_effects(x)
Run Code Online (Sandbox Code Playgroud)

哪个更好?为什么?

python list-comprehension

97
推荐指数
4
解决办法
8534
查看次数

正确使用列表推导 - python

通常,列表推导用于从现有列表中导出新列表.例如:

>>> a = [1, 2, 3, 4, 5]
>>> [i for i in a if i > 2]
[3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

我们应该用它们来执行其他程序吗?例如:

>>> a = [1, 2, 3, 4, 5]
>>> b = []
>>> [b.append(i) for i in a]
[None, None, None, None, None]
>>> print b
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

或者我应该避免上述内容而是使用以下内容?:

for i in a:
    b.append(i)
Run Code Online (Sandbox Code Playgroud)

python list-comprehension

11
推荐指数
1
解决办法
1288
查看次数

标签 统计

list-comprehension ×2

python ×2