简体   繁体   English

用列表理解替换while循环

[英]replacing while loop with list comprehension

It is common to express for loops as list comprehensions: 将循环表达为列表推导是很常见的:

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

This is equivalent to: 这相当于:

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

Is there any sort of mechanism by which this sort of iteration could be done with a while loop? 是否有任何一种机制可以通过while循环完成这种迭代?

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

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? 当然,通过这个简单的例子,很容易转换为for循环,然后转换为列表理解,但如果不是那么容易呢?

eg 例如

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

(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.) (当然上面的伪代码不是合法的python)(对于这种事情,我想到了itertools ,但我不太清楚这个模块。)

EDIT 编辑

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

This could translate to: 这可以转化为:

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)] 

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 '*'? 但是,我认为,while循环容易读取(而不是有索引错误)另外,如果你的对象(DT)支持“+”而不是“*”? More complicated examples could happen if maxtime somehow changes for each iteration of the loop... 如果maxtime以某种方式改变循环的每次迭代,就会发生更复杂的例子......

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循环只是检查一个正在递增的局部变量,你应该将它转换为for循环或等效列表理解。

You should only use a while loop only if you can not express the loop as iterating over something. 只有当你不能将循环表示为迭代某些东西时,才应该使用while循环。 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. 因此(正确使用)while循环很少见,最好写出来。 A while comprehension would just make them harder to read. 一段时间的理解只会让他们更难阅读。

If you just want to return multiple values, you should consider writing a generator . 如果您只想返回多个值,则应考虑编写生成器

For example, your edited algorithm should be written as (using numpy.arange ): 例如,您编辑的算法应该写为(使用numpy.arange ):

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

Alternatively, with a generator: 或者,使用发电机:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM