【问题标题】:Repeat Index Of Loop [duplicate]循环的重复索引[重复]
【发布时间】:2021-11-02 04:24:08
【问题描述】:

如何重复 for 循环的索引?

for path in directory:
   
   ...
   
   if ...:
      stop here and
      repeat the current index of the for loop
   ...

我称之为重启^^

【问题讨论】:

  • 您正在寻找的概念是redo,它是 Perl 和 Ruby 中的关键字,可以满足您的需求。不幸的是,Python 没有等效的功能。
  • 你需要一个 do-while 循环,遗憾的是,它在 Python 中也不存在。因此,将其替换为 while 循环:X; while condition: X。

标签: python loops for-loop indexing


【解决方案1】:
for path in directory:
   X
   if C:
      stop here and
      repeat the current index of the for loop
   Y

变成

for path in directory:
   while True:
      X
      if not C:
         break
   Y

【讨论】:

  • 这太可怕了,但是......是的,这是在 Python 中执行这种控制流模式的正确方法。我建议重构以不惜一切代价避免它,但这是正确的答案。
  • @SilvioMayolo 我想我们也可以将directory 包装在一个具有.redo() 方法的迭代器中,这样就可以让他们的方式...
  • @SilvioMayolo 哦,太好了,有人already did 就是这样。
猜你喜欢
  • 2013-08-11
  • 1970-01-01
  • 2013-03-19
  • 1970-01-01
  • 2017-11-15
  • 2020-02-06
  • 2012-10-19
  • 2011-06-16
  • 2021-07-16
相关资源
最近更新 更多