用列表理解替换while循环 [英] replacing while loop with list comprehension

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

问题描述

通常将for循环表示为列表推导:

It is common to express for loops as list comprehensions:

mylist=[]
for i in range(30):
    mylist.append(i**2)

这等效于:

mylist = [i**2 for i in range(30)]

是否有某种机制可以通过while循环完成这种迭代?

Is there any sort of mechanism by which this sort of iteration could be done with a while loop?

mylist=[]
i=0
while i<30:
    mylist.append(i**2)
    i+=1

当然,通过这个简单的示例,可以很容易地将其转换为for循环,然后转换为列表理解,但是如果不是那么简单怎么办?

Of course with this simple example it's easy to translate to a for loop and then to a list comprehension, but what if it isn't quite so easy?

例如

mylist = [i**2 while i=0;i<30;i++ ]

(当然,上面的伪代码不是合法的python)(itertools是我想到的这种东西,但我对这个模块并不十分了解.)

(Of course the above pseudo-code isn't legitimate python) (itertools comes to mind for this sort of thing, but I don't know that module terribly well.)

编辑

一个我认为需要一段时间理解的示例(非常简单)将是:

An (very simple) example where I think a while comprehension would be useful would be:

dt=0.05
t=0
mytimes=[]
while t<maxtime:
   mytimes.append(t)
   t+=dt

这可以翻译为:

dt=0.05
t=0
nsteps=maxtime/dt
mytimes=[]
for t in (i*dt for i in xrange(nsteps)):
    mytimes.append(t)

可以写成(复合)列表理解:

which can be written as a (compound) list comprehension:

nsteps=maxtime/dt
mytimes=[t for t in (i*dt for i in xrange(nsteps)] 

但是,我认为while循环更容易阅读(并且没有索引错误),而且,如果您的对象(dt)支持'+'但不支持'*',该怎么办?如果maxtime对于循环的每次迭代都以某种方式更改,则可能会发生更复杂的示例...

But, I would argue that the while loop is MUCH easier to read (and not have index errors) Also, what if your object (dt) supports '+' but not '*'? More complicated examples could happen if maxtime somehow changes for each iteration of the loop...

推荐答案

如果while循环justs检查正在递增的局部变量,则应将其转换为for循环或等效的列表理解.

If your while loop justs checks a local variable that is being incremented, you should convert it to a for loop or the equivalent list comprehension.

仅当您可以不能将循环表示为迭代某些内容时,才应使用while循环.典型用例的一个例子是检查事件或状态调用本机代码的低级循环.因此,(正确使用)while循环很少,最好将其写出来. 同时理解只会使它们更难阅读.

You should only use a while loop only if you can not express the loop as iterating over something. An example of a typical use case are checks for the state of an Event, or a low-level loop that calls into native code. It follows that (correctly used) while loops are rare, and best just written out. A while comprehension would just make them harder to read.

如果只想返回多个值,则应考虑编写生成器.

If you just want to return multiple values, you should consider writing a generator.

例如,您编辑后的算法应写为(使用 numpy.arange ):

For example, your edited algorithm should be written as (using numpy.arange):

mytimes = numpy.arange(0, maxtime, 0.05)

或者,使用生成器:

def calcTimes(maxtime):
  dt = 0.05
  t = 0
  while t < maxtime:
   yield t
   t += dt

这篇关于用列表理解替换while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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