簡體   English   中英

在教程中被enumerate()函數所混淆

[英]Confused by the enumerate() function in tutorials

實際上,我正在使用一些先前編寫的腳本來學習python,我試圖逐行理解代碼,但是在這段代碼中,我不知道到底發生了什么(特別是在第2行中):

def convertSeq(s, index):
    result = [i + 1 for i, ch in enumerate(s) if ch == '1']
    result = ' '.join([str(index) + ':' + str(i) for i in result])
    result = str(index) + ' ' + result
    return result

謝謝

enumerate返回一個iterator( enumerate object ),它從傳遞給它的iterable / itertator生成包含索引和項的tuples

>>> text = 'qwerty'
>>> it = enumerate(text)
>>> next(it)
(0, 'q')
>>> next(it)
(1, 'w')
>>> next(it)
(2, 'e')
>>> list(enumerate(text))
[(0, 'q'), (1, 'w'), (2, 'e'), (3, 'r'), (4, 't'), (5, 'y')]

因此,代碼中的列表理解實際上等效於:

>>> text = '12121'
>>> result = []
for item in enumerate(text):
    i, ch = item              #sequence unpacking
    if ch == '1':
        result.append(i+1)
...         
>>> result
[1, 3, 5]

實際上,您還可以將索引的起點傳遞給枚舉,因此您的列表組合可以更改為:

result = [i for i, ch in enumerate(s, start=1) if ch == '1']

enumerate通常比這樣更受歡迎:

>>> lis = [4, 5, 6, 7]
for i in xrange(len(lis)):
    print i,'-->',lis[i]
...     
0 --> 4
1 --> 5
2 --> 6
3 --> 7

更好:

>>> for ind, item in enumerate(lis):
    print ind,'-->', item
...     
0 --> 4
1 --> 5
2 --> 6
3 --> 7

enumerate也將在迭代器上工作:

>>> it = iter(range(5, 9))      #Indexing not possible here
for ind, item in enumerate(it):
    print ind,'-->', item
...     
0 --> 5
1 --> 6
2 --> 7
3 --> 8

enumerate幫助:

class enumerate(object)
 |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 |  
 |  Return an enumerate object.  iterable must be another object that supports
 |  iteration.  The enumerate object yields pairs containing a count (from
 |  start, which defaults to zero) and a value yielded by the iterable argument.
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

枚舉迭代器上的迭代,並返回帶有當前索引和當前項的元組。

>>> for i in range(100,105):
...     print(i)
... 
100
101
102
103
104
>>> for info in enumerate(range(100,105)):
...     print(info)
... 
(0, 100)
(1, 101)
(2, 102)
(3, 103)
(4, 104)

它從任何可迭代對象創建一個新的迭代器,該迭代器返回原始對象中的值以及從0開始的索引。 例如

lst = ["spam", "eggs", "tomatoes"]

for item in lst:
  print item

# spam
# eggs
# tomatoes

for i, item in enumerate(lst):
   print i, item

# 0 spam
# 1 eggs
# 2 tomatoes

enumarate是python的內置函數,可幫助您跟蹤序列的索引。

請參見以下代碼:

    >>>sequence = ['foo', 'bar', 'baz']
    >>>
    >>>list(enumerate(sequence)) # prints [(0, 'foo'), (1, 'bar'), (2, 'baz')]
    >>>
    >>>zip(range(len(sequence)), sequence) # prints [(0, 'foo'), (1, 'bar'), (2, 'baz')]
    >>>for item in sequence:
    ......print (item, sequence.index(item))
    ('foo', 0)
    ('bar', 1)
    ('baz', 2)

如您所見,結果是相同的,但通過枚舉可以更容易地進行寫入和讀取,並且在某些情況下更有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM