Monday, July 2, 2007

python tip

Assumed that a sample.txt file contains multiple headline, which are same as the line0. In order to keep line0 as the only head line, and delete the rest line in the middle of file, we have the following 2 implementation:

Trivial:

ls = open("sample.txt").readlines()
k = ls[0]
for l in ls[1:] :
if l.find("File") < 0:
k += l
then k contains what I want

Python way :

from operator import add
filter_line0 = lambda line0, lines: reduce ( add, filter ( lambda line : line.find(line0) < 0, lines ))
k = ls[0]+filter_line0(ls[0], ls[1:])

The trivial way is easy to understand, but hard to reuse. in order to reuse these code, we have to copy block of code or define these code as a function, However, the python way express intuitive way as one line function definition, then you can use it anywhere.

No comments: