想想我正在调用它的副作用的函数,而不是返回值(比如打印到屏幕,更新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中如何使用title()方法?
是仅针对单个项目还是也针对整个列表?
第一个打印有效,第二个打印返回错误。为什么?
animals = ['dog', 'cat', 'whale', 'koala', 'panda']
print(f"\nname of the 3rd animal: {animals[2].title()}")
print(f"\nname of all animals: {animals.title()}")
Run Code Online (Sandbox Code Playgroud)
第一个打印有效,第二个打印返回错误。为什么?