for或while循环做n次 [英] for or while loop to do something n times

查看:181
本文介绍了for或while循环做n次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,有两种好的方法可以不止一次地重复某些操作。其中之一是,而循环,另一个是循环的。所以让我们看看两个简单的代码:

pre $ 对于范围(n)中的i:
do_sth( )



另外:

  i = 0 
while i< n:
do_sth()
i + = 1

我的问题是他们更好。当然,第一个在文档示例和各种代码中可以在Internet上找到的代码非常常见,它更加优雅和简短,但是另一方面,它会创建一个完全无用的整数列表来循环他们。这不是浪费内存,特别是大量的迭代?

那么你认为,哪种方式更好?

解决方案


但是另一方面,它创建了一个完全无用的整数列表来循环它们。这不是浪费内存,特别是就大量迭代而言?

这就是 xrange(n)是for。在Python 3中, xrange()重命名为 range() - 如果你想要一个列表,你必须通过 list(range(n))


In Python you have two fine ways to repeat some action more than once. One of them is while loop and the other - for loop. So let's have a look on two simple pieces of code:

for i in range(n):
    do_sth()

And the other:

i = 0
while i < n:
    do_sth()
    i += 1

My question is which of them is better. Of course, the first one, which is very common in documentation examples and various pieces of code you could find around the Internet, is much more elegant and shorter, but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

So what do you think, which way is better?

解决方案

but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.

In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).

这篇关于for或while循环做n次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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