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

Fredrik Lundh fredrik at pythonware.com
Thu Oct 12 16:33:29 EDT 2006


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