MST

星途 面试题库

面试题:Python列表推导式性能优化及场景分析

假设有一个非常大的列表,其中包含100万个随机整数。现在要从这个列表中筛选出所有能被3整除且大于100的数,你会使用列表推导式还是普通循环?详细阐述你的选择原因,并通过代码实现,同时使用`timeit`模块来测量两者的运行时间。
29.7万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

选择列表推导式的原因

列表推导式的代码更加简洁,可读性好,在处理这类简单的筛选任务时,Python解释器可以对其进行优化,执行效率通常比普通循环高。

代码实现

import timeit

# 生成包含100万个随机整数的列表
import random
large_list = [random.randint(1, 1000) for _ in range(1000000)]

# 使用列表推导式筛选
def list_comprehension():
    return [num for num in large_list if num % 3 == 0 and num > 100]

# 使用普通循环筛选
def normal_loop():
    result = []
    for num in large_list:
        if num % 3 == 0 and num > 100:
            result.append(num)
    return result

# 测量列表推导式的运行时间
lc_time = timeit.timeit(list_comprehension, number = 100)
# 测量普通循环的运行时间
nl_time = timeit.timeit(normal_loop, number = 100)

print(f"列表推导式运行100次的时间: {lc_time} 秒")
print(f"普通循环运行100次的时间: {nl_time} 秒")

运行时间测量结果分析

通过timeit模块测量多次运行的时间,一般情况下,列表推导式的运行时间会比普通循环短,这是因为列表推导式在底层实现上利用了Python的优化机制,而普通循环需要更多的解释器开销。具体的运行时间差异可能因机器性能和Python版本有所不同。