如何重置遍历集合的循环? [英] How to reset a loop that iterates over a set?

查看:129
本文介绍了如何重置遍历集合的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何重置在集合上迭代的循环?遍历列表的常见答案是重置用于访问列表的索引,但是集合不支持索引.

How can I reset a loop that iterates over a set? A common answer for iterating over a list is to reset the index you are using to access the list, however sets do not support indices.

关键是要能够迭代大量对象,对每个元素执行一些操作,直到结果与我需要的结果匹配为止.我要搜索的功能是重置循环的功能.意思是从头开始重新进行迭代,以确保无论出于何种原因我都能再次访问每个元素.

The point is to be able to iterate over a large set of objects, perform some action against each element until a result matches the result I require. The functionality I am searching for is the ability to reset a loop. Meaning restart the iteration from the beginning to ensure I visit every element again for whatever reason.

如何重置以下循环?

for element in some_set:
   print element
   if element + offset == needed_result:
      # reset

针对此特定问题,我使用python 2.7,但我也欢迎python 3解决方案.

I'm using python 2.7 for this specific problem, but I'd also welcome python 3 solutions.

推荐答案

一种方法是使用迭代器.您可以通过简单地在集合上调用iter()并在每次迭代中调用其next方法来定义迭代器.满足条件后,您可以简单地从集合中再次创建迭代器对象,然后重复该过程:

One way to do so would be by using iterators. You could define an iterator by simply calling iter() on your set, and call its next method on each iteration. When the condition is met, you can simply create again the iterator object from the set and repeat the process:

s = {1,2,3,4,5}
s_ = iter(s)
# Just a counter to avoid endless loop
cont = 0
while cont < 10:
    try:
        i = next(s_)
    except StopIteration:
        break
    # Some condition
    if flag == True: 
        # Reset the iterator when the condition is met
        s_ = iter(s) 
        continue
    cont += 1

这篇关于如何重置遍历集合的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆