在Python for循环中创建一个计数器

这个问题在这里已经有了答案:

  • 访问'for'循环中的索引? 17个答案

  • 这(在for循环之前创建一个额外的变量)不是pythonic。

    在具有额外计数器时迭代项目的pythonic方法是使用enumerate

    for index, item in enumerate(iterable):
        print(index, item)
    

    因此,例如对于一个列表lst这将是:

    lst = ["a", "b", "c"]
    
    for index, item in enumerate(lst):
      print(index, item)
    

    ...并生成输出:

    0 a
    1 b
    2 c
    

    强烈建议您尽可能使用Python的内置函数来创建“pythonic解决方案”。 还有枚举的文档。


    如果您需要更多关于枚举的信息,您可以查看PEP 279 - 枚举()内置函数。

    链接地址: http://www.djcxy.com/p/24007.html

    上一篇: Creating a counter inside a Python for loop

    下一篇: How to get the index of the iterator object?