conditionals in lambdas?

Fredrik Lundh fredrik at effbot.org
Fri Nov 3 15:40:23 EST 2000


Michael wrote:
> filecontents = open(filename, "r").readlines()
> filecontents = filter(filterloaddata, filecontents)
>
> def filterloaddata(string):
>     if string[:9] == '#LOADDATA':
>         return 1
>     else:
>         return 0

oh, but "string[:9] == '#LOADDATA' is an expression, which
returns zero if false, and a non-zero (1, actually) if true.

try this:

    filter(lambda s: s[:9] == '#LOADDATA', filecontents)

or better:

    filter(lambda s: s.startswith('#LOADDATA'), filecontents)

or, if you're using 2.0:

    [line for line in filecontents if line.startswith('#LOADDATA')]

</F>





More information about the Python-list mailing list