我想知道 len() 是如何工作的。
每次我调用 len() 时,它是否从列表的开头到结尾进行计数,或者,由于 list 也是一个类,len() 是否只返回列表对象中记录列表长度的变量?
另外,我希望有人能告诉我在哪里可以找到“len()”、“map()”等内置函数的源代码。
在此处下载 Python 2.7 源代码:http://www.python.org/getit/releases/2.7.4/ http://www.python.org/getit/releases/2.7.4/
list
实施于./Include/listobject.h
and ./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()
列表的常数时间操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)