问题描述
我正在阅读Python中的文本处理,我发现了一个
评论,这有助于我在新的视角中看到循环。我想
因为我已经习惯了C风格的循环,你在循环声明中创建了一个计数器
,for循环在我看来总是如此
关于做某些事情的事情,而不是在一个物体上迭代
。
这种区别的原因来自我读了很多的事实
如何使用范围而且有点气馁,因为它没有
真的使用for循环来实现它真实的目的。所以我的问题是,这是
只是一个关于for循环的Python导向的观点,还是一般的想法?
此外,如果你*如果* *需要做一些次数的事情。
这没关系,还是意味着你正在接近问题
错误?使用for和range一起似乎是一个常见的习惯用语,但同时又气馁,所以我很想知道什么是平衡。
谢谢。
I''m reading Text Processing in Python right now and I came across a
comment that is helping me to see for loops in a new light. I think
because I''m used to the C-style for loop where you create a counter
within the loop declaration, for loops have always seemed to me to be
about doing something a certain number of times, and not about iterating
over an object.
The reason for this distinction comes from the fact that I read a lot
how using range and for is somewhat discouraged, because it doesn''t
really use a for loop for it''s true purpose. So my question is, is this
just a Python-oriented opinion about for loops, or is it a general idea?
Also, what if you *do* need to just do something a set number of times.
Is this okay, or does it mean you are approaching the problem
incorrectly? Using for and range together seems to be a common idiom,
yet at the same time discouraged, so I''m wondering what is a good balance.
Thanks.
推荐答案
通常你''使用范围或xrange。 range在
内存中建立一个完整的列表,如果数量很大,那么可能会很昂贵。 xrange只计算
到那个数字。
Normally you''d use range or xrange. range builds a complete list in
memory so can be expensive if the number is large. xrange just counts
up to that number.
你真的需要做吗?某事多次?如果是这样,范围
(或xrange)非常适合这项工作。但更常见的是,你需要为每一个< what>"做一次
,所以把你的''whatevers''放在
列表中并迭代那个。
-
Ben Sizer
Do you really need to do something "a number of times"? If so, range
(or xrange) is perfect for the job. More often though, you need to do
something "once for every <whatever>", so put your ''whatevers'' in a
list and iterate over that.
--
Ben Sizer
这篇关于在for循环中使用range()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!