A few beginning questions

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Jul 15 05:17:42 EDT 2003


"richardc" <richardc at hmgcc.gov.uk> wrote in
news:3f13bd77$1 at mail.hmgcc.gov.uk: 

> 1. How do tyou do enum's in python, infact dose anybody know of a C++
> -> Python crossreference doc out there ?

The only way to do enums in Python is to define a bunch of constants. 
Either put them in a module, or alternatively define them as class 
attributes. However, you may find there is less call for enums in Python 
than in C++, for example in C++ you might use enums to tokenise short 
strings, but in Python you would just use the strings to represent 
themselves.

e.g. You could use any of these:

  UP, DOWN, LEFT, RIGHT = range(4)
  move(UP)

or:

  class DIRECTION:
      UP, DOWN, LEFT, RIGHT = range(4)

  move(DIRECTION.UP)

or:

  move('up')


> 3. How do I reverse iterate through a loop ... is there an easier way
> than something like the following
>     l = ['some', 'text', 'in', 'a', 'list' ]
>     for i in range( 0, len( l ) ):
>         do something to l[ i ]

The usual way is simply to reverse the list before iterating over it.

     l = ['some', 'text', 'in', 'a', 'list' ]
     l_reversed = l.reverse()
     for item in l_reversed:
         do something to item

> 
> 4. Is there an easy way to reverse read a file ?  I mean like a
> 'getline' that works by reading backwards through the file.  Im
> guessing getting single characters and moving the file pointer back is
> going to be slow in python. Its not actally that important... just
> wondering 
> 
If the file isn't too large you can call the readlines() method and simply 
reverse the result as above. You may find this incovenient for very large 
files though. I can't think of many cases where I would want to read a 
whole file in reverse, if all you want is the last few lines of a massive 
file then just seek near the end before reading the remainder and reverse 
the resulting list of lines. If you really do need all of the file in 
reverse, then you could write a generator to read it backwards in fixed 
size chunks and split each chunk into lines.


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list