【问题标题】:Get times looped in a for loop in Python获取在 Python 中的 for 循环中循环的时间
【发布时间】:2018-10-11 20:18:33
【问题描述】:

我想获取我在 for 循环中循环的次数

for x in dictionary:
    print(timeslooped) # If the looped has looped 4 times then this should print 4

我该怎么做?

这是一个非常简单的问题,但我最近学习了 Python,但我不确定。谢谢!

【问题讨论】:

  • 做一个枚举?
  • 调用enumerate或在之后(如果基于0)或之前(如果基于1)增加一个整数变量以获取实际索引。

标签: python for-loop


【解决方案1】:

你可以使用计数器:

timeslooped = 0
for x in dictionary:
    timeslooped +=1
    print(timeslooped) # If the looped has looped 4 times then this should print 4

或使用enumerate:

for timeslooped, x in enumerate(dictionary): # enumerate returns the index and the value as a tuple
    print(timeslooped) 

【讨论】:

  • 计数器对我来说更直观。
【解决方案2】:

enumerate可以告诉你

for timeslooped, x in enumerate(dictionary):
    print(timeslooped+1)

添加了+1,因为它将从0而不是1开始

【讨论】:

  • enumerate中的第二个参数可以指定起始索引enumerate(dictionary,1)
  • 呵呵,一直在使用enumerate,我从来不知道你能做到这一点
猜你喜欢
  • 2011-03-10
  • 2020-10-18
  • 2022-10-20
  • 1970-01-01
  • 2011-10-18
  • 1970-01-01
  • 2013-08-28
  • 1970-01-01
相关资源
最近更新 更多