paseline(my favorite simple script): does something similar exist?

RickMuller rpmuller at gmail.com
Sun Oct 15 12:47:47 EDT 2006


Amazing! There were lots of great suggestions to my original post, but
I this is my favorite.

Rick

Fredrik Lundh wrote:
> RickMuller wrote:
>
> > I'm posting this here because (1) I'm feeling smug at what a bright
> > little coder I am
>
> if you want to show off, and use a more pythonic interface, you can do
> it with a lot fewer lines.  here's one example:
>
> def parseline(line, *types):
>      result = [c(x) for (x, c) in zip(line.split(), types) if c] or [None]
>      return len(result) != 1 and result or result[0]
>
> text = "H    0.000   0.000   0.000"
>
> print parseline(text, str, float, float, float)
> print parseline(text, None, float, float, float)
> print parseline(text, None, float)
>
> etc.  and since you know how many items you'll get back from the
> function, you might as well go for the one-liner version, and do
> the unpacking on the way out:
>
> def parseline(line, *types):
>      return [c(x) for (x, c) in zip(line.split(), types) if c] or [None]
>
> text = "H    0.000   0.000   0.000"
>
> [tag, value] = parseline(text, str, float)
> [value] = parseline(text, None, float)
> 
> </F>




More information about the Python-list mailing list