想想我正在调用它的副作用的函数,而不是返回值(比如打印到屏幕,更新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)
哪个更好?为什么?
我希望我的y轴刻度标签在刻度值为正时为绿色,在刻度值为负时为红色.
考虑以下系列和情节
np.random.seed([3,1415])
pd.Series(np.random.randn(100)).add(.1).cumsum().plot()
Run Code Online (Sandbox Code Playgroud)
我需要[2, 4, 6, 8]绿色和[-2, -4, -6, -8]红色.