My Big Dict.
Paul Simmonds
psimmo60 at hotmail.com
Thu Jul 3 07:32:21 EDT 2003
Christian Tismer <tismer at tismer.com> wrote in message news:<mailman.1057162092.18394.python-list at python.org>...
> Paul Simmonds wrote:
> ...
> I'm not trying to intrude this thread, but was just
> struck by the list comprehension below, so this is
> about readability.
<snipped>
> >
> > d=dict([(l[:l.index('!')],l[l.index('!')+1:-1])\
> > for l in file('test.txt') if l.count('!')])
>
> With every respect, this looks pretty much like another
> P-language. The pure existance of list comprehensions
> does not try to force you to use it everywhere :-)
>
Quite right. I think that mutation came from the fact that I was
thinking in C all day. Still, I don't even write C like that...it
should be put to sleep ASAP.
<snip>
> > d={}
> > for l in file("test.txt"):
> > try: i=l.index('!')
> > except ValueError: continue
> > d[l[:i]]=l[i+1:]
>
> About speed: I'm not sure with the current Python
> version, but it might be worth trying to go without
> the exception:
>
> d={}
> for l in file("test.txt"):
> i=l.find('!')
> if i >= 0:
> d[l[:i]]=l[i+1:]
>
> and then you might even consider to split on the first
> "!", but I didn't do any timings:
>
> d={}
> for l in file("test.txt"):
> try:
> key, value = l.split("!", 1)
> except ValueError: continue
> d[key] = value
>
Just when you think you know a language, an optional argument you've
never used pops up to make your life easier. Thanks for pointing that
out.
I've done some timings on the functions above, here are the results:
Python2.2.1, 200000 line file(all data lines)
try/except with split: 3.08s
if with slicing: 2.32s
try/except with slicing: 2.34s
So slicing seems quicker than split, and using if instead of
try/except appears to speed it up a little more. I don't know how much
faster the current version of the interpreter would be, but I doubt
the ranking would change much.
Paul
More information about the Python-list
mailing list