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函數的任意迭代。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章