标签归档:enumerate

enumerate()是什么意思?

问题:enumerate()是什么意思?

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

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

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

What does enumerate mean in this context?


回答 0

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

因此,对于其中的每个元素cursor,将生成一个元组(counter, element);的for环结合,要row_numberrow分别。

演示:

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

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

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

如果要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)

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

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

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


回答 1

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

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

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

版画

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

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

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.


回答 2

我正在阅读Brett Slatkin 的书(《Effective Python》),他展示了另一种遍历列表的方法,并且知道列表中当前项目的索引,但是他建议最好不要使用它,enumerate而应该使用它。我知道您问过枚举是什么意思,但是当我理解以下内容时,我也了解了如何enumerate遍历列表,同时又更容易了解当前项目的索引(并且更具可读性)。

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

输出为:

0 a
1 b
2 c

我也曾经做过一些事情,甚至在阅读有关该enumerate功能之前变得更加愚蠢。

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

它产生相同的输出。

但是enumerate我只需要写:

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

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 but he suggests that it is better not to use it and to use enumerate instead. 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).

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.

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

It produces the same output.

But with enumerate I just have to write:

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

回答 3

正如其他用户所提到的那样,enumerate是一个生成器,它在可迭代项的每个项旁边添加一个增量索引。

因此,如果您有一个要说的清单l = ["test_1", "test_2", "test_3"]list(enumerate(l))它将为您提供以下信息:[(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]

现在,什么时候有用?一个可能的用例是当您要遍历项目时,并且想要跳过仅知道列表中其索引但不知道其值的特定项目(因为当时尚不知道其值)。

for index, value in enumerate(joint_values):
   if index == 3:
       continue

   # Do something with the other `value`

因此,您的代码读起来更好,因为您也可以执行常规的for循环,range但随后访问需要为其编入索引的项目(即joint_values[i])。

尽管另一个用户提到了enumerateusing 的实现zip,但我认为没有使用一种更纯净(但稍微复杂一点)的方法itertools如下:

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

例:

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

输出:

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

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

如评论中所提到的,这种具有范围的方法不适用于任意可迭代对象,就像原始enumerate函数一样。

As other users have mentioned, enumerate is a generator that adds an incremental index next to each item of an iterable.

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

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 (i.e., 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:

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’)]

As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate function does.


回答 4

枚举函数的工作方式如下:

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)

输出是

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

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