简体   繁体   English

如何在python中的for循环中跳过下一个迭代?

[英]How to skip the next iteration during a for loop in python?

I have the following code that runs breadth first search (bfs) on a list of graph vertices. 我有以下代码在图顶点列表上运行广度优先搜索(bfs)。

Currently I have code that is running bfs on every item in the list, but I want to make it so that if the next item in the for loop is already in the set of discovered nodes, then the for loop should skip over it, so that bfs does not have to be performed on every vertex. 当前,我在列表中的每个项目上都有运行bfs的代码,但是我想这样做,以便如果for循环中的下一个项目已经在发现的节点集中,那么for循环应该跳过它,因此不必在每个顶点上都执行bfs。

My main reason for doing this is because I have to read in a very large file, so it causes a memory crash when I perform bfs on every vertex; 我这样做的主要原因是因为我必须读一个非常大的文件,所以当我在每个顶点上执行bfs时,这会导致内存崩溃; my code works on small test cases but not on the large file. 我的代码适用于小型测试用例,但不适用于大型文件。

I know the continue statement allows you to skip over the current iteration, but I can't figure how to skip the next iteration. 我知道continue语句允许您跳过当前迭代,但是我不知道如何跳过下一个迭代。

Any help is appreciated; 任何帮助表示赞赏; thank you. 谢谢。

def count_components(g):
    dictionary = {}
    dict_list = {}
    for i in g.vertices():
      dictionary = breadth_first_search(g,i)
      dictionary_keys = list(dictionary.keys())
      dict_list[i] = dictionary_keys
    for value in dict_list.values():
      for i in range(len(value)):
        value[i] = str(value[i])
    result = {}
    for key, value in dict_list.items():
      dict_list[key].sort(key=str.lower)
      if value not in result.values():
        result[key] = value
    count = len(result)
    return count

Two options, which you pick is up to you: 您可以选择以下两个选项:

1) Start your loop with a guard clause. 1)使用guard子句开始循环。 This lets you call continue and skip that iteration of the loop. 这使您可以调用continue并跳过该循环的迭代。

>>> values = [0,1,2,1,0]
>>> known = set([2])
>>> for i in values:
...   if i in known:
...     continue
...   print i
...   known.add(i)
...
0
1

2) Use a generator in the for statement: 2)在for语句中使用生成器:

>>> values = [0,1,2,1,0]
>>> known = set([2])
>>> for i in (x for x in values if not x in known):
...   print i
...   known.add(i)
...
0
1

Which is best is up to you. 哪个最好取决于您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM