a good explanation

rainbow.cougar at gmail.com rainbow.cougar at gmail.com
Fri May 26 15:53:59 CEST 2006


Nick Craig-Wood wrote:
> mik3 <mik3l3374 at hotmail.com> wrote:
> >  So he has written his first program in python and i have roughly toook
> >  a glance at it and saw what he did.. i pointed out his "mistakes" but
> >  couldn't convince him otherwise. Anyway , i am going to show him your
> >  replies..
>
> You might want to show him this too...if you happen to need cnt in the
> loop, this is what you write
>
>   files = [a,b,c,d]
>   for cnt, fi in enumerate(files):
>      do_something(cnt, fi)
>
> --
> Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick

Like many things in Python, measurement is the key, Being an old C
coder. I quite often write:

i=0
while i<end_condition:
    something=stuff[i]
    i++

and try to be a good pythonesita translate it to:
for something in stuff:
   #stuff code

A few weeks ago I found myself manipulating a list of lists that I
wanted to use as columns and discovered that in:

  def resort(list,d2list):
    newlist=[]
    """
    while (i < d2len):
      newlist.append(list[d2list[i][1]])
      i+=1
    """
    for row in d2list:
      newlist.append(list[row[1]])


    return newlist


ran as fast with the while as the for.  However, for 'elegance', and to
stick to python style, I kept the for.

Something that is being missed is the idea of changing conditions. A
for loop assumes known boundaries.

def condition_test():
  # check socket status
  # return true if socket good, false otherwise

while condition_test():
   # do stuff

allows the loopiing code to react to changing conditions. Which of
couse is why we like to keep while loops around ;-0

Curtis




More information about the Python-list mailing list