1

实际上我正在使用一些以前编写的脚本来学习 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

谢谢

4

4 回答 4

1

enumerate返回一个迭代器( ),它从传递给它的迭代器/迭代器enumerate object中产生包含索引和项目。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]), ...
于 2013-11-01T09:13:20.890 回答
0

enumerate 遍历一个迭代器,并返回一个具有当前索引和当前项的元组。

>>> 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)
于 2013-11-01T09:11:06.427 回答
0

它从任何可迭代对象创建一个新的迭代器,该迭代器返回原始对象中的值以及从 开始的索引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
于 2013-11-01T09:13:25.070 回答
0

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)

如您所见,结果是相同的,但使用 enumerate 更容易编写、读取并且在某些情况下效率更高。

于 2013-11-01T09:16:59.197 回答