[Tutor] 2 problems in a small script
Dick Moores
rdm at rcblue.com
Fri Oct 12 16:36:02 CEST 2007
At 05:35 AM 10/12/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>At 03:41 AM 10/12/2007, Kent Johnson wrote:
>>> finalList = [ word for word in lstA if all(c in astr for c in word) ]
>>I'm just not comfortable with list comprehensions yet,
>
>Hmm, too bad. I use list comps and generator expressions constantly.
>
>>but I see that although yours is very succinct, it's clear enough.
>
>Or maybe *because* it is succinct. Most list comps and genexps are
>either applying a function to every element of a list (map):
>[ f(x) for x in seq ]
>
>or filtering a list:
>[ x for x in seq if f(x) ]
>
>and occasionally both:
>[ f(x) for x in seq if g(x) ]
>
>where f and g could be actual functions or simple expressions.
>
>I think the reason I like them so much is because they are succinct,
>high-level, and flow in the same order as my thoughts. For example,
>the requirement "Give me a list of the square of every element of
>seq" translates directly to
>[ # Give me a list
>x*x # of the square
>for x in seq ] # of every element of seq
>
>and "I need a list of every element in seq that is > 2" becomes
>[ # I need a list
>x for x in seq # of every element in seq
>if x>2 ] # that is > 2
>
>I have a writeup here:
>http://personalpages.tds.net/~kent37/kk/00003.html
>
>Kent
Terrific, Kent. I promise I'll use 'em whenever I can. And I'll also
try again to understand generators:
<http://docs.python.org/tut/node11.html#SECTION00111000000000000000000>.
But I'll begin with the section just before that, on iterators:
<http://docs.python.org/tut/node11.html#SECTION0011900000000000000000>.
Looks like tough going..
Dick
More information about the Tutor
mailing list