在Python中从1循环到无穷大
在C语言中,我会这样做:
int i;for (i = 0;; i++)
if (thereIsAReasonToBreak(i))
break;
如何在Python中实现类似的功能?
回答:
使用itertools.count:
import itertoolsfor i in itertools.count(start=1):
if there_is_a_reason_to_break(i):
break
在Python
2,range()并xrange()仅限于sys.maxsize。在Python
3中range()可以更高,尽管不能达到无穷大:
import sysfor i in range(sys.maxsize**10): # you could go even higher if you really want
if there_is_a_reason_to_break(i):
break
因此,最好使用count()。
以上是 在Python中从1循环到无穷大 的全部内容, 来源链接: utcz.com/qa/405462.html

