Newbie question about file input
Dan Schmidt
dfan at harmonixmusic.com
Mon Aug 16 17:44:22 EDT 2004
Grant Edwards <grante at visi.com> writes:
| If you want to be particularly obtuse we can rely on the fact
| that True evaluates to 1 and and False evaluates to 0, and just
| sum up the boolean values returned by .startswith(). That only
| takes one line (not counting the "import operator"):
|
| print reduce(operator.add,[l.startswith('[Event') for l in file('test.pgn','r')])
I'd just write something like
print len( [ l for l in file( 'test.pgn') if l.startswith( '[Event' ) ] )
which actually looks clear enough to me that I might write it that way
if I were writing this program.
If anonymous functions weren't so ugly I might use
print len( filter( lambda l: l.startswith( '[Event' ), file( 'test.pgn' ) ) )
instead, since I find the [ l for l ] idiom for filter kind of unappealing.
Dan
--
http://www.dfan.org
More information about the Python-list
mailing list