本文介绍了在Python中从1循环到无穷大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,我会这样做:

In C, I would do this:

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

如何在Python中实现类似的目的?

How can I achieve something similar in Python?

推荐答案

使用 itertools.count :

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

在Python2中,xrange()仅限于sys.maxint,对于大多数实际目的而言可能已足够:

In Python2 xrange() is limited to sys.maxint, which may be enough for most practical purposes:

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

在Python3中,range()可以提高很多,尽管不能达到无穷大:

In Python3, range() can go much higher, though not to infinity:

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

因此,最好使用count().

这篇关于在Python中从1循环到无穷大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 04:57