相关疑难解决方法(0)

为什么Python的'len'函数比__len__方法更快?

在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()更快.为什么?

python python-internals

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

len()函数在python 3中是如何实现的以及如何找到python中内置函数的源代码?

这个探索从一个简单的 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)

现在,我有两个问题:

  1. 如何在不手动在GitHub上搜索源代码的情况下查找内置函数的源代码?
  2. len函数内部如何工作?

我对此有两个假设:

  1. Python 将所有东西都视为一个对象,它们有一个名为 length(或类似的东西)的属性,每当我从列表中弹出一个元素时。该属性减 1。
  2. 另一个假设是 python 以某种方式迭代整个对象并返回长度。

我得到了源代码。然而,它再次使用另一个函数来计算长度。

static PyObject *
builtin_len(PyObject *module, PyObject *obj)
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/ …
Run Code Online (Sandbox Code Playgroud)

c python python-3.x

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

标签 统计

python ×2

c ×1

python-3.x ×1

python-internals ×1