重做Python中的循环迭代

时间:2016-04-12 12:36:21

标签: python python-2.7 for-loop redo

Python是否有某种语言存在的“重做”语句?

(“redo”语句是一个声明(就像“break”或“continue”一样)会影响循环行为 - 它会在最里面的循环开始时跳转并再次开始执行它。)

6 个答案:

答案 0 :(得分:6)

不,它没有。我建议使用while循环并将check变量重置为初始值。

count = 0
reset = 0
while count < 9:
   print 'The count is:', count
   if not someResetCondition:
       count = count + 1

答案 1 :(得分:4)

不,Python没有redo的直接支持。一个选项可能涉及嵌套循环,如:

for x in mylist:
    while True:
        ...
        if shouldredo:
            continue  # continue becomes equivalent to redo
        ...
        if shouldcontinue:
            break     # break now equivalent to continue on outer "real" loop
        ...
        break  # Terminate inner loop any time we don't redo

但这意味着break外部循环在“redo - 能”块中是不可能的,不需要求助于异常,标记变量或将整个事物打包为函数。

或者,您使用直接while循环复制for循环为您执行的操作,显式创建和推进迭代器。它有自己的问题(默认情况下continue实际上是redo,你必须明确地推进“真实”continue的迭代器,但它们并不可怕(只要它您评论continue的使用,以明确您打算redocontinue,以避免混淆维护者)。要允许redo和其他循环操作,您可以执行以下操作:

# Create guaranteed unique sentinel (can't use None since iterator might produce None)
sentinel = object()
iterobj = iter(mylist)  # Explicitly get iterator from iterable (for does this implicitly)
x = next(iterobj, sentinel)  # Get next object or sentinel
while x is not sentinel:     # Keep going until we exhaust iterator
    ...
    if shouldredo:
        continue
    ...
    if shouldcontinue:
        x = next(iterobj, sentinel)  # Explicitly advance loop for continue case
        continue
    ...
    if shouldbreak:
        break
    ...
    # Advance loop
    x = next(iterobj, sentinel)

以上也可以使用try / except StopIteration:代替带有next的2-arg sentinel来完成,但是将整个循环包裹起来会冒其他来源的风险StopIteration被抓住,并且在内部和外部next调用的适当范围内进行此操作将非常难看(比基于sentinel的方法更糟糕。)

答案 2 :(得分:2)

我在学习perl时遇到同样的问题,我找到了这个页面。

按照perl的书:

my @words = qw(fred barney pebbles dino wilma betty);
my $error = 0;

my @words = qw(fred barney pebbles dino wilma betty);
my $error = 0;

foreach (@words){
    print "Type the word '$_':";
    chomp(my $try = <STDIN>);
    if ($try ne $_){
        print "Sorry - That's not right.\n\n";
        $error++;
        redo;
    }
}

以及如何在Python上实现它? 按照代码:

tape_list=['a','b','c','d','e']

def check_tape(origin_tape):
    errors=0
    while True:
        tape=raw_input("input %s:"%origin_tape)
        if tape == origin_tape:
            return errors
        else:
            print "your tape %s,you should tape %s"%(tape,origin_tape)
            errors += 1
            pass

all_error=0
for char in tape_list:
    all_error += check_tape(char)
print "you input wrong time is:%s"%all_error

Python没有&#34;重做&#34;语法,但我们可以制作一个&#39; while&#39;在某个函数中循环,直到得到我们想要的列表。

答案 3 :(得分:0)

这是我使用迭代器的解决方案:

favicons
  • 需要明确class redo_iter(object): def __init__(self, iterable): self.__iterator = iter(iterable) self.__started = False self.__redo = False self.__last = None self.__redone = 0 def __iter__(self): return self def redo(self): self.__redo = True @property def redone(self): return self.__redone def __next__(self): if not (self.__started and self.__redo): self.__started = True self.__redone = 0 self.__last = next(self.__iterator) else: self.__redone += 1 self.__redo = False return self.__last # Display numbers 0-9. # Display 0,3,6,9 doubled. # After a series of equal numbers print -- iterator = redo_iter(range(10)) for i in iterator: print(i) if not iterator.redone and i % 3 == 0: iterator.redo() continue print('---')
  • continue是一项额外功能
  • 对于Python2,请使用redone代替def next(self)
  • 要求在循环
  • 之前定义def __next__(self)

答案 4 :(得分:0)

使用while并在循环结束时使用增量,没有非常软化但易于阅读。因此,中间的任何continue都会产生重做效果。样本重做3的每个倍数:

redo = True # To ends redo condition in this sample only
i = 0
while i<10:
   print(i, end='')
   if redo and i % 3 == 0:
      redo = False # To not loop indifinively in this sample
      continue # Redo
   redo = True
   i += 1

结果:00123345667899

答案 5 :(得分:0)

python中没有重做。 一个很容易理解的解决方案如下:

for x in mylist:
    redo = True
    while redo:
        redo = False

        If should_redo:
            redo = True

很明显,不添加评论

Continue就像在for循环中一样工作

但是break不可用,这solution使break可用,但是代码不太清楚。