开始使用免费开始使用

时间测量 II

正如我们在讲解中所讨论的,在大多数情况下,列表推导式比 for 循环更快。

在这个演示中,您将看到一种情形:列表推导式与 for 循环在效率上的差异非常小,以至于无论选择哪种方法,都能立刻完成这个简单任务。

列表 words 中包含从互联网下载的随机单词。我们的目标是创建另一个名为 listlet 的列表,只保留以字母 b 开头的单词。

如果您对在 Python 中处理字符串还不熟悉:每个字符串都有 .startswith() 属性。它会返回一个布尔值,表示该字符串是否以某个特定字母或短语开头。

本练习是课程的一部分

使用 pandas 编写高效代码

查看课程

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Store the time before the execution
start_time = time.___()

# Execute the operation
letlist = [wrd for wrd in words if wrd.startswith('b')]

# Store and print the difference between the start and the current time
total_time_lc = time.time() - ___
print('Time using list comprehension: {} sec'.format(total_time_lc))
编辑并运行代码