# 在Python中从1到无限循环

``int i; for (i = 0;; i++) if (thereIsAReasonToBreak(i)) break;` `

### 9 Solutions collect form web for “在Python中从1到无限循环”

` `import itertools for i in itertools.count(): if there_is_a_reason_to_break(i): break` `

` `import sys for i in xrange(sys.maxint): if there_is_a_reason_to_break(i): break` `

` `import sys for i in range(sys.maxsize**10): # you could go even higher if you really want if there_is_a_reason_to_break(i): break` `

` `def to_infinity(): index=0 while 1: yield index index += 1 for i in to_infinity(): if i > 10:break` `

` `from itertools import takewhile, count def thereIsAReasonToContinue(i): return not thereIsAReasonToBreak(i) for i in takewhile(thereIsAReasonToContinue, count()): pass # or something else` `

` `from itertools import takewhile, count for i in takewhile(lambda x : not thereIsAReasonToBreak(x), count()): pass # or something else` `

`takewhile`模仿一个“行为良好”的C for循环：你有一个继续条件，但是你有一个生成器而不是一个任意的expression式。 在C for循环中你可以做的事情是“performance不好”，比如在循环体中修改`i` 。 如果生成器是关于某个局部variables`i`的closures，那么也可以模仿这些。 从某种意义上说，定义这个闭包使得你在做一些可能会让你的控件结构混淆的东西特别明显。

` `int i = 0; while (! thereIsAReasonToBreak (i)) { // do something i++; }` `

` `int i; // *may* be better inside the for statement to localise scope for (i = 0; ! thereIsAReasonToBreak (i); i++) { // do something }` `

` `i = 0 while not thereIsAReasonToBreak (i): # do something i += 1` `

` `i = 0 while not there_is_reason_to_break(i): # some code here i += 1` `

` `from itertools import count for i in count(): if thereIsAReasonToBreak(i): break` `

` `while 1==1: if want_to_break==yes: break else: # whatever you want to loop to infinity` `

` `a = 1 while a: if a == Thereisareasontobreak(a): break a += 1` `

` `m=1 for i in range(m): #action here m+=1` `

` `list=[0] for x in list: list.append(x+1) print x` `

• 在Python中，如何迭代一个迭代器，然后迭代另一个迭代器？
• 在文件之间使用全局variables？