Thinking Pythonically (was Re: gah! I hate the new string syntax)

Mark Pilgrim f8dy at diveintopython.org
Fri Mar 2 17:45:33 EST 2001


in article 97p3mh$bkm$1 at tyfon.itea.ntnu.no, Magnus Lie Hetland at
mlh at idi.ntnu.no wrote on 3/2/01 4:31 PM:
> "Mark Pilgrim" <f8dy at yahoo.com> wrote in message
> news:97oupq$qijrh$1 at ID-77331.news.dfncis.de...
> [snip]
>>>>> vobs = [line.replace('Tag:', '').strip() for line in output if
>> line[:4]=='Tag:']
>>>>> vobs
>> ['/vobs/intranet', '/vobs/project']
> 
> I can't resist fiddling with little snippets of code... Why don't you
> use:
> 
>>>> vobs = [line[4:-1] for line in output if line[:4] == 'Tag:']

Actually, for the same reason the original poster complained about the
original code snippet: my version reads more like natural language.  (It
also, I realized after posting, assumes that the VOB name doesn't contain
'Tag:', which I know it won't, but that wasn't clear from the example.)
"For each line in the output, if the line starts with 'Tag:', cut out the
'Tag:' part and strip the whitespace, and give me a list of all of those."
That's a pretty direct mapping from code to description.

My original point, in case it got lost in the details, was that I like list
comprehensions because they force me to think Pythonically.  By that I mean
thinking in terms of the things that Python is good at, like lists and
dictionaries.  These are rich data structures with lots of built-in
capabilities, and if I don't use them, I may as well go back to programming
in Powerbuilder: writing WHILE loops to do progressive searches through
strings when I really want something like the above example, using SELECT
CASE statements for jump tables when all I really want is a dictionary of
functions, and so forth.

-M
You're smart; why haven't you learned Python yet?
http://diveintopython.org/






More information about the Python-list mailing list