实际上,我正在使用一些先前编写的脚本学习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
返回一个迭代器(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]), ...
关于python - 在教程中被enumerate()函数所混淆,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19723729/