为了支持对集合的索引,Python包括enumerate()函数.它提供了收集索引.
for index, item in enumerate(list):
# do domething
print index
在我的情况下,我有一个巨大的列表,并想知道使用enumerate()手动创建索引是否更快?例如
index = 0
for item in list:
# do something
print index
index = index + 1
解决方法:
枚举函数内置;它不会先验地计算元素.以下是C-code implementation:
static PyObject *
enum_next(enumobject *en)
{
PyObject *next_index;
PyObject *next_item;
PyObject *result = en->en_result;
PyObject *it = en->en_sit;
next_item = (*it->ob_type->tp_iternext)(it);
if (next_item == NULL)
return NULL;
next_index = PyInt_FromLong(en->en_index);
if (next_index == NULL) {
Py_DECREF(next_item);
return NULL;
}
en->en_index++;
if (result->ob_refcnt == 1) {
Py_INCREF(result);
Py_DECREF(PyTuple_GET_ITEM(result, 0));
Py_DECREF(PyTuple_GET_ITEM(result, 1));
} else {
result = PyTuple_New(2);
if (result == NULL) {
Py_DECREF(next_index);
Py_DECREF(next_item);
return NULL;
}
}
PyTuple_SET_ITEM(result, 0, next_index);
PyTuple_SET_ITEM(result, 1, next_item);
return result;
}
因此,该函数动态产生下一个en整数.