list comprehension help

Alex Martelli aleax at mac.com
Mon Mar 19 00:52:39 CET 2007


f<cptnwillard at gmail.com> wrote:

> I wonder whether the following be more efficient if DB was a
> dictionnary:
> 
> Splits = (line.split(' ') for line in open('file.text', 'r'))
> DB = dict([(S[0], S[-1]) for S in Splits])

You'd still be doing much more splitting work (and behind-the-scene
allocation and freeing of memory) than strictly needed (only meaningful
for lines that are really big).

Also, lose the brackets immediately inside the ( ) in the second line --
no need to take up huge amounts of memory (by a list comprehension) when
you're only going to work on one item at a time anyway (so a genexp
suffices).

The observation that either the line or the S[-1] entry needs to be
subjected to a .rstrip('\n') also still holds here.

Use python -mtimeit to measure the runtimes of various alternatives --
be careful about what you place in -s (initialization, not looped-upon
and not measured) and what you don't (that _will_ be looped upon, and
measured).


Alex



More information about the Python-list mailing list