相关疑难解决方法(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中是否有没有结果的地图?

有时候,我只想为一个条目列表执行一个函数 - 例如:

for x in wowList:
   installWow(x, 'installed by me')
Run Code Online (Sandbox Code Playgroud)

有时我需要这些东西用于模块初始化,所以我不希望在全局命名空间中有像x这样的足迹.一种解决方案是将map与lambda一起使用:

map(lambda x: installWow(x, 'installed by me'), wowList)
Run Code Online (Sandbox Code Playgroud)

但这当然会创建一个很好的列表[无,无,...]所以我的问题是,如果有一个没有返回列表的类似函数 - 因为我只是不需要它.

(当然我也可以使用_x,因此不会留下可见的足迹 - 但地图解决方案看起来很整洁......)

python iteration

27
推荐指数
5
解决办法
1万
查看次数

将没有返回值的方法应用于列表的每个元素

有没有办法在列表推导中使用没有返回值的方法,例如random.shuffle?

>>> import pprint
>>> import random
>>> 
>>> L = [ random.shuffle(range(5)) for x in range(5)]
>>> 
>>> print L
[None, None, None, None, None]
Run Code Online (Sandbox Code Playgroud)

这是将random.shuffle方法应用于列表中每个项目的for循环:

>>> L = [ range(5) for x in range(5) ]
>>> pprint.pprint(L)
[[0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4]]
>>> for element in L:
...     random.shuffle(element)
... 
>>> pprint.pprint(L)
[[2, 0, 3, 1, 4],
 [2, …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension

9
推荐指数
2
解决办法
3753
查看次数

标签 统计

python ×3

list-comprehension ×2

iteration ×1