replacing while loop with list comprehension

2019-07-17 01:18发布

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?

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?

e.g.

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

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 '*'? More complicated examples could happen if maxtime somehow changes for each iteration of the loop...

1条回答
Lonely孤独者°
2楼-- · 2019-07-17 01:58

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.

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.

For example, your edited algorithm should be written as (using 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
查看更多
登录 后发表回答