本文翻译自:What does enumerate() mean?

What does for row_number, row in enumerate(cursor): do in Python? 什么for row_number, row in enumerate(cursor):在Python中做什么?

What does enumerate mean in this context? enumerate在这种情况下意味着什么?


#1楼

参考:https://stackoom.com/question/1V1pm/enumerate-是什么意思


#2楼

The enumerate() function adds a counter to an iterable. enumerate()函数向iterable添加计数器。

So for each element in cursor , a tuple is produced with (counter, element) ; 因此,对于cursor每个元素,使用(counter, element)生成元组; the for loop binds that to row_number and row , respectively. for循环分别将其绑定到row_numberrow

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: 默认情况下, enumerate()0开始计数,但如果给它第二个整数参数,它将从该数字开始:

>>> 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; 如果你要在Python中重新实现enumerate() ,这里有两种实现方法; one using itertools.count() to do the counting, the other manually counting in a generator function : 一个使用itertools.count()进行计数,另一个使用生成器函数手动计数:

from itertools import countdef enumerate(it, start=0):# return an iterator that adds a counter to each element of itreturn zip(count(start), it)

and

def enumerate(it, start=0):count = startfor 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). C中的实际实现更接近后者,优化for i, ...的公共重用单个元组对象for i, ...解包案例并使用计数器的标准C整数值,直到计数器变得太大而不能使用Python整数对象(无界限)。


#3楼

It's a builtin generator function, see http://docs.python.org/2/library/functions.html#enumerate . 它是内置生成器函数,请参阅http://docs.python.org/2/library/functions.html#enumerate 。

In short, it yields the elements of an iterator, as well as an index number: 简而言之,它产生迭代器的元素,以及索引号:

for item in enumerate(["a", "b", "c"]):print item

prints 版画

(0, "a")
(1, "b")
(2, "c")

It's helpful if you want to loop over an interator, and also want to have an index counter available. 如果你想循环遍历一个interator,并且想要一个索引计数器,它会很有用。 If you want the counter to start from some other value (usually 1), you can give that as second argument to enumerate . 如果您希望计数器从其他值(通常为1)开始,您可以将其作为enumerate第二个参数。


#4楼

The enumerate function works as follows: 枚举函数的工作原理如下:

doc = """I like movie. But I don't like the cast. The story is very nice"""
doc1 = doc.split('.')
for i in enumerate(doc1):print(i)

The output is 输出是

(0, 'I like movie')
(1, " But I don't like the cast")
(2, ' The story is very nice')

#5楼

I am reading a book ( 'Effective Python' ) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list. 我正在阅读Brett Slatkin的一本书( 'Effective Python' ),他展示了另一种迭代列表的方法,并且还知道列表中当前项目的索引。 BUT suggests to not use it and use enumerate instead. 但建议不要使用它,而是使用enumerate I know you asked what enumerate means, but when I understood the following, I also understood how enumerate makes iterating over a list while knowing the index of the current item easier (and more readable). 我知道你问的枚举意味着什么,但是当我理解了以下内容时,我也理解了enumerate如何在知道当前项的索引更容易(更易读)的同时迭代列表。

list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):letter = list_of_letters[i]print (i, letter)

The output is: 输出是:

0 a
1 b
2 c

I also used to do something, even sillier before I read about the enumerate function. 在我阅读enumerate函数之前,我还习惯做一些事情,甚至更愚蠢。

i = 0
for n in list_of_letters:print (i, n)i = i +1

It produces the same output. 它产生相同的输出。

But with enumerate I just have to write: 但是enumerate我只需要写:

list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):print (i, letter)

#6楼

As other users have mentioned, enumerate is a generator that adds an incremental index next to each item of an iterable. 正如其他用户所提到的, enumerate是一个生成器,它在迭代的每个项旁边添加一个增量索引。

So if you have a list say l = ["test_1", "test_2", "test_3"] , the list(enumerate(l)) will give you something like this: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')] . 所以如果你有一个列表说l = ["test_1", "test_2", "test_3"]list(enumerate(l))会给你这样的东西: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]

Now, when this is useful? 现在,这有用吗? A possible use case is when you want to iterate over items, and you want to skip a specific item that you only know its index in the list but not its value (because its value is not known at the time). 一个可能的用例是当你想迭代项目时,你想要跳过一个你只知道列表中的索引而不是它的值的特定项目(因为它的值当时是未知的)。

for index, value in enumerate(joint_values):if index == 3:continue# Do something with the other `value`

So your code reads better because you could also do a regular for loop with range but then to access the items you need to index them (ie, joint_values[i] ). 因此,您的代码读取更好,因为您还可以使用range执行常规for循环,然后访问索引它们所需的项目(即joint_values[i] )。

Although another user mentioned an implementation of enumerate using zip , I think a more pure (but slightly more complex) way without using itertools is the following: 虽然另一个用户提到使用zip实现enumerate ,但我认为不使用itertools方式更纯粹(但稍微复杂一点)如下:

def enumerate(l, start=0):return zip(range(start, len(l) + start), l)

Example: 例:

l = ["test_1", "test_2", "test_3"]
enumerate(l)
enumerate(l, 10)

Output: 输出:

[(0, 'test_1'), (1, 'test_2'), (2, 'test_3')] [(0,'test_1'),(1,'test_2'),(2,'test_3')]

[(10, 'test_1'), (11, 'test_2'), (12, 'test_3')] [(10,'test_1'),(11,'test_2'),(12,'test_3')]

As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate function does. 正如评论中所提到的,这种带范围的方法不适用于原始enumerate函数的任意迭代。

enumerate()是什么意思?相关推荐

  1. Python 常用内置函数map、zip、filter、reduce、enumerate

    Python 中有许多非常实用的内置函数,通过这些函数我们可以方便的实现某些功能,下面就列举一些常用的内置函数. 1. map() 函数 map() 可以根据提供的函数对指定序列做映射,它接受一个函数 ...

  2. Python enumerate() 函数的使用

    enumerate() 函数 在 Python 2.3. 以上版本可用 enumerate() 函数的作用: enumerate() 函数用于将一个可遍历的数据对象(如列表.元组或字符串)组合为一个索 ...

  3. python公共操作(运算符(+、*、in、not in)、公共方法(len()、del、max()、min()、range()、enumerate())、类型转换(tuple、list、set))

    1. 运算符 1.1 + # 1. 字符串 str1 = 'aa' str2 = 'bb' str3 = str1 + str2 print(str3) # aabb # 2. 列表 list1 = ...

  4. python中的enumerate 函数(编号的实现方式)

    enumerate 函数用于遍历序列中的元素以及它们的下标: 默认从0开始,如果想从1开始,可以仿照最后案例 加上逗号,和数字编号 >>> for i,j in enumerate( ...

  5. enumerate在python中的意思_Python中enumerate用法详解

    enumerate()是python的内置函数.适用于python2.x和python3.x enumerate在字典上是枚举.列举的意思 enumerate参数为可遍历/可迭代的对象(如列表.字符串 ...

  6. range函数python循环次数查询_python进阶教程之循环相关函数range、enumerate、zip

    在"循环"一节,我们已经讨论了Python基本的循环语法.这一节,我们将接触更加灵活的循环方式. range() 在Python中,for循环后的in跟随一个序列的话,循环每次使用 ...

  7. Python 中的 enumerate 函数

    enumerate 函数用于遍历序列中的元素以及它们的下标: >>> for i,j in enumerate(('a','b','c')):print i,j 0 a 1 b 2 ...

  8. Python的enumerate()的坑

    其实enumerate()函数本身没啥问题,通常使用方法如下: 然而我踩的坑是这样的,最近项目中使用TensorFlow,生成TFRecord数据集,训练完成后在测试集上测试,发现预期能分的好的类别分 ...

  9. python enumerate()用法

    enumerate enumerate()函数用于将一个可遍历的数据对象(如列表.元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在for循环当中.Python2.3.以上版本可用,2 ...

  10. python内置函数:iter、enumerate和next

    文章目录 iter.enumerate iter enumerate iter.next iter.enumerate 共同点:都可以可以用来访问可迭代对象 区别:前者访问迭代对象时只返回元素,后者除 ...

最新文章

  1. mac mysql5.7 my_【mysql】Mac下安装mysql5.7 完整步骤,大坑已解决
  2. ×××论坛应该为访问者更大的价值
  3. vue笔记整理与总结
  4. P2577 [ZJOI2005]午餐
  5. 前端学习(1705):前端系列javascript之原型中的this
  6. 移动端返回上一页实现方法
  7. 高三了,一模距本科线还差22,英语才28,怎么办啊
  8. 自定义添加的鼠标事件
  9. 使用python对文件下的文件批量重命名
  10. 一篇文章帮你梳理清楚API设计时需要考虑的几个关键点
  11. 机房计算机配置思维导图,运用思维导图培养高中学生信息技术学科核心素养
  12. BI系统打包Docker镜像及容器化部署的具体实现
  13. 大学课程表模板html,课程表模板空白表格(小/中/大学课程表模板excel) 中文免费版...
  14. 微信小程序优购商城项目总结
  15. linux4.12内核 bridge简介
  16. 5G时代的到来,对网络公关将产生哪些深远影响?
  17. jupyter notebook无法连接python3服务器内核 一直显示正在连接服务器
  18. 无线测温采集设备及无线测温监控系统的选型指导-安科瑞王婧
  19. Facebook被封锁后如何申请解除
  20. 韩老师讲SQL2005数据库开发 环境准备代码

热门文章

  1. 2009-09-神秘东北大哥
  2. C语言中的scanf对应java中的,什么是C++中的scanf,memset和一对夫妇在Java中的含义?...
  3. 智融SW6106、SW6206、SW6208,移动电源市场主流协议快充IC
  4. 创造与魔法游戏服务器无限金币,创造与魔法无限金币版
  5. 列表,字典,字符串初识,以及一些用法
  6. 亚马逊佣金计算:各个类目下的佣金比和最低推荐费
  7. ZeroTier部署moon服务端以及配置客户端
  8. 浅谈对HashMap的理解,以及对HashMap部分源码的分析
  9. uni-app接入高德地图SDK实现定位用户城市
  10. 机车出入库相关、调车转线、、后期杂谈