enumerate() 是什么意思? [英] What does enumerate() mean?

查看:45
本文介绍了enumerate() 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for row_number, row in enumerate(cursor): 在 Python 中有什么作用?

enumerate 在这种情况下是什么意思?

解决方案

enumerate() 函数 向可迭代对象添加一个计数器.

所以对于cursor中的每个元素,都会用(counter, element)生成一个元组;for 循环将其分别绑定到 row_numberrow.

演示:

<预><代码>>>>元素 = ('foo', 'bar', 'baz')>>>对于元素中的元素:... 打印元素...富酒吧巴兹>>>对于计数,枚举(元素)中的元素:...打印计数,元素...0 富1 条2巴兹

默认情况下,enumerate()0 开始计数,但如果你给它第二个整数参数,它将从那个数字开始:

<预><代码>>>>对于计数,枚举中的元素(元素,42):...打印计数,元素...42 英尺43 巴44 巴兹

如果您要在 Python 中重新实现 enumerate(),这里有两种实现方式;一种使用 itertools.count() 进行计数,另一个在生成器函数中手动计数:

from itertools 导入计数def enumerate(it, start=0):# 返回一个迭代器,为它的每个元素添加一个计数器返回 zip(count(start), it)

def enumerate(it, start=0):计数 = 开始对于其中的元素:产量(计数,元素)计数 += 1

C 中的实际实现 更接近后者, 优化重用单个元组对象用于常见的 for i, ... 解包情况并使用标准的 C 整数值作为计数器,直到计数器变得太大而无法避免使用 Python 整数对象(这是无界的).

What does for row_number, row in enumerate(cursor): do in Python?

What does enumerate mean in this context?

解决方案

The enumerate() function adds a counter to an iterable.

So for each element in cursor, a tuple is produced with (counter, element); the for loop binds that to row_number and row, respectively.

Demo:

>>> elements = ('foo', 'bar', 'baz')
>>> for elem in elements:
...     print elem
... 
foo
bar
baz
>>> for count, elem in enumerate(elements):
...     print count, elem
... 
0 foo
1 bar
2 baz

By default, enumerate() starts counting at 0 but if you give it a second integer argument, it'll start from that number instead:

>>> for count, elem in enumerate(elements, 42):
...     print count, elem
... 
42 foo
43 bar
44 baz

If you were to re-implement enumerate() in Python, here are two ways of achieving that; one using itertools.count() to do the counting, the other manually counting in a generator function:

from itertools import count

def enumerate(it, start=0):
    # return an iterator that adds a counter to each element of it
    return zip(count(start), it)

and

def enumerate(it, start=0):
    count = start
    for elem in it:
        yield (count, elem)
        count += 1

The actual implementation in C is closer to the latter, with optimisations to reuse a single tuple object for the common for i, ... unpacking case and using a standard C integer value for the counter until the counter becomes too large to avoid using a Python integer object (which is unbounded).

这篇关于enumerate() 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆