【问题标题】:What is the function of enumerate in my code? [duplicate]我的代码中枚举的功能是什么? [复制]
【发布时间】:2016-05-03 20:14:01
【问题描述】:

我做了一些代码,基本上可以找到句子中单词的索引,但我真的不明白我做了什么以及枚举的功能是什么?

    sentence = ['The', 'cat','sat', 'on', 'the', 'mat']
    for index, word in enumerate(sentence):
        print (index, word)

【问题讨论】:

标签: python python-3.x enumerate


【解决方案1】:

documentation 会告诉你更多你需要知道的信息:

返回一个枚举对象。 iterable 必须是序列、迭代器或其他支持迭代的对象。 enumerate() 返回的迭代器的__next__() 方法返回一个元组,其中包含一个计数(从 start 开始,默认为 0)和通过迭代 iterable 获得的值。

相当于:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2013-12-15
    • 2014-04-28
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多