gpt4 book ai didi

python - 对教程中的 enumerate() 函数感到困惑

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:02 25 4
gpt4 key购买 nike

实际上我正在使用一些以前编写的脚本学习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),它会生成tuples,其中包含传递给它的 iterable/itertator 中的索引和项。

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

有关枚举的帮助:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com