Efficient grep using Python?
Fredrik Lundh
fredrik at pythonware.com
Wed Dec 15 11:48:59 EST 2004
Tim Peters wrote:
>> bdict = dict.fromkeys(open(bfile).readlines())
>>
>> for line in open(afile):
>> if line not in bdict:
>> print line,
>>
>> </F>
>
> Note that an open file is an iterable object, yielding the lines in
> the file. The "for" loop exploited that above, but fromkeys() can
> also exploit it. That is,
>
> bdict = dict.fromkeys(open(bfile))
>
> is good enough (there's no need for the .readlines()).
(sigh. my brain knows that, but my fingers keep forgetting)
and yes, for this purpose, "dict.fromkeys" can be replaced
with "set".
bdict = set(open(bfile))
(and then you can save a few more bytes by renaming the
variable...)
</F>
More information about the Python-list
mailing list