相关疑难解决方法(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
查看次数

将 title() 方法与列表一起使用

在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)

第一个打印有效,第二个打印返回错误。为什么?

python list title

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

标签 统计

python ×2

list ×1

list-comprehension ×1

title ×1