gpt4 book ai didi

python - 为什么 any() 比 in 快这么多?

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:54 25 4
gpt4 key购买 nike

https://repl.it/@ArmanTavakoli/List-Comprehension-vs-Any

为什么我的 any 检查速度比我的 in 检查速度快得多,而它们实际上在做同样的事情?

from timeit import default_timer as timer
import random

input = [random.randint(0, 100) for x in range(0, 1000000)]

def any_check(input):
return any(i == 1 for i in input)

def list_comprehension(input):
return 1 in [num for num in input]

first_start = timer()
any_check(input)
first_end = timer()
print('any_check', first_end - first_start)

second_start = timer()
list_comprehension(input)
second_end = timer()
print('list_comprehension', second_end - second_start)

各函数运行 3 次的结果。

# Calculated with 3 runs each
# Ratio is list_comprehension:any_check

# 10,000 - Mean Ratio: 17.87
# Example run;
# any_check 1.5022000297904015e-05
# list_comprehension 0.00038980199315119535

# 100,000 - Mean Ratio: 140.76
# any_check 2.020499960053712e-05
# list_comprehension 0.0035961729954578914

# 1,000,000 - Mean Ratio: 3379.81
# any_check 2.2904998331796378e-05
# list_comprehension 0.08528400499926647

最佳答案

正如一些人在评论中指出的那样,您的函数执行 in 的原因测试比使用 any 的版本慢是因为该函数 包含一个不必要的列表理解,它需要在 in 之前遍历整个输入。运算符(operator)可以开始寻找匹配项。在列表上运行时,inany可以短路,如果在搜索早期找到匹配值,则提前退出。但是你的第二个函数中的列表理解总是遍历整个输入,即使有一个 1。就在一开始。

如果你替换了1 in [num for num in input]1 in input ,您会发现性能与使用 any 的函数一样好或更好。 .如果input,性能将非常相似是一个列表,但对于其他容器类型(例如 set s 和 range s)可能要快得多。

关于python - 为什么 any() 比 in 快这么多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55132375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com