在Python中,len是一个通过调用对象的__len__方法来获取集合长度的函数:
def len(x):
return x.__len__()
Run Code Online (Sandbox Code Playgroud)
所以我希望直接呼叫__len__()至少能够达到最快速度len().
import timeit
setup = '''
'''
print (timeit.Timer('a="12345"; x=a.__len__()', setup=setup).repeat(10))
print (timeit.Timer('a="12345"; x=len(a)', setup=setup).repeat(10))
Run Code Online (Sandbox Code Playgroud)
但使用上述代码进行测试的结果显示len()更快.为什么?
这个探索从一个简单的 LeetCode 问题开始。我正在学习 python 并试图解决 leetcode 中的一个问题,其中我在检查 while 循环中的条件时使用了len() 。我很好奇如果我在 while 中写入len(nums)我的程序会进行更多计算。为了找到这个问题,我开始寻找源代码。
while i < len(nums):
#if both the numbers are same we can pop the ith number
#else just increase the index and return the length in the end.
if nums[i] == val:
nums.pop(i)
else:
i+=1
return len(nums)
Run Code Online (Sandbox Code Playgroud)
现在,我有两个问题:
我对此有两个假设:
我得到了源代码。然而,它再次使用另一个函数来计算长度。
static PyObject *
builtin_len(PyObject *module, PyObject *obj)
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/ …Run Code Online (Sandbox Code Playgroud)