My Big Dict.
Christian Tismer
tismer at tismer.com
Wed Jul 2 12:08:18 EDT 2003
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.
> If this is a problem, use a combination of count and index methods to
> find the first, and use slices. For example, if you don't mind
> two-lined list comps:
>
> 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 :-)
...
compared to this:
...
> d={}
> for l in file("test.txt"):
> try: i=l.index('!')
> except ValueError: continue
> d[l[:i]]=l[i+1:]
which is both faster in this case and easier to read.
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
cheers -- chris
--
Christian Tismer :^) <mailto:tismer at tismer.com>
Mission Impossible 5oftware : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/
14109 Berlin : PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776
PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04
whom do you want to sponsor today? http://www.stackless.com/
More information about the Python-list
mailing list