enumerate()是什么意思?

本文翻译自: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 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). 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函数的任意迭代。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值