Python enumerate() 是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22171558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:25:23  来源:igfitidea点击:

What does enumerate() mean?

pythonenumerate

提问by user3374098

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

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

What does enumeratemean in this context?

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

回答by Martijn Pieters

The enumerate()functionadds a counter to an iterable.

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

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

因此,对于 中的每个元素cursor,都会生成一个元组(counter, element);的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 0but if you give it a second integer argument, it'll start from that number instead:

默认情况下,enumerate()从 at 开始计数,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; one using itertools.count()to do the counting, the other manually counting in a generator function:

如果您要enumerate()在 Python 中重新实现,这里有两种方法可以实现;一个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 Cis 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, ...解包情况下重用单个元组对象,并使用标准的 C 整数值作为计数器,直到计数器变得太大而无法避免使用 Python 整数对象(这是无界)。

回答by RemcoGerlich

It's a builtin function that returns an object that can be iterated over. See the documentation.

它是一个内置函数,它返回一个可以迭代的对象。请参阅文档

In short, it loops over the elements of an iterable (like a list), as well as an index number, combined in a tuple:

简而言之,它循环遍历可迭代对象(如列表)的元素以及索引号,并组合在一个元组中:

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 a sequence (or other iterable thing), and also want to have an index counter available. If you want the counter to start from some other value (usually 1), you can give that as second argument to enumerate.

如果您想遍历一个序列(或其他可迭代的东西),并且还希望有一个可用的索引计数器,这会很有帮助。如果您希望计数器从某个其他值(通常为 1)开始,您可以将其作为第二个参数提供给enumerate

回答by Ashok Kumar Jayaraman

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')

回答by Dora

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 buthe suggests that it is better not to use it and to use enumerateinstead. I know you asked what enumerate means, but when I understood the following, I also understood how enumeratemakes iterating over a list while knowing the index of the current item easier (and more readable).

我正在阅读Brett Slatkin 的一本书(Effective Python),他展示了另一种迭代列表的方法,并且还知道列表中当前项目的索引,他建议最好不要使用它,enumerate而是使用它。我知道你问 enumerate 是什么意思,但是当我理解以下内容时,我也理解了如何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 enumeratefunction.

在我读到这个enumerate函数之前,我也曾经做过一些事情,甚至更愚蠢。

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

It produces the same output.

它产生相同的输出。

But with enumerateI just have to write:

enumerate我只需要写:

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

回答by Rafael

As other users have mentioned, enumerateis 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')].

所以如果你有一个列表 say 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 rangebut then to access the items you need to index them (i.e., joint_values[i]).

所以你的代码读起来更好,因为你也可以做一个常规的 for 循环,range然后访问你需要索引它们的项目(即,joint_values[i])。

Although another user mentioned an implementation of enumerateusing zip, I think a more pure (but slightly more complex) way without using itertoolsis the following:

虽然另一位用户提到了enumerateusing的实现zip,但我认为不使用更纯粹(但稍微复杂一点)的方法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')]

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

[(0, 'test_1'), (1, 'test_2'), (2, '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 enumeratefunction does.

正如评论中提到的,这种带范围的方法不能像原始enumerate函数那样处理任意可迭代对象。