【问题标题】:How to Python count list lengthPython如何计算列表长度
【发布时间】:2013-04-27 07:14:39
【问题描述】:

我想知道 len() 是如何工作的。

每次调用 len() 时是否从列表的开始计数到结尾,或者,由于列表也是一个类,所以 len() 是否只返回列表对象中记录列表长度的变量?

另外,我希望有人能告诉我在哪里可以找到'len()'、'map()'等内置函数的源代码。

【问题讨论】:

标签: python python-2.7


【解决方案1】:

在此处下载 Python 2.7 源代码:http://www.python.org/getit/releases/2.7.4/

list 在./Include/listobject.h 和./Objects/listobject.c 中实现。

typedef struct {
    PyObject_VAR_HEAD
    /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
    PyObject **ob_item;

    /* ob_item contains space for 'allocated' elements.  The number
     * currently in use is ob_size.
     * Invariants:
     *     0 <= ob_size <= allocated
     *     len(list) == ob_size
     *     ob_item == NULL implies ob_size == allocated == 0
     * list.sort() temporarily sets allocated to -1 to detect mutations.
     *
     * Items must normally not be NULL, except during construction when
     * the list is not yet visible outside the function that builds it.
     */
    Py_ssize_t allocated;
} PyListObject;

list.__len__() 只是咨询ob_size,它是PyObject_VAR_HEAD 的一部分。这使得len() 成为列表的恒定时间操作。

【讨论】:

【解决方案2】:

嗯,你可以找到内置函数的文档here。

list 数据类型跟踪它所持有的元素数量,len(list) 是一个 O(1) 操作。


源码可以在the download page找到Python源码。

【讨论】:

    猜你喜欢
    • 2011-08-07
    • 2015-05-09
    • 2022-06-16
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多