Nebie: list question, speed
Uwe Hoffmann
nospam at nospam.de
Sat May 5 14:55:52 EDT 2001
Werner Hoch wrote:
>
> Hello,
>
> I wrote a little programm parsing two textfiles together.
> The result is a list without uniq entries:
>
> So i wrote this to check if the entry already exists:
> --------
> if ergfield.count(ergline) == 0:
> ergfield.append(ergline)
> ---------
> execution time is about 45 seconds
>
> an then I tried a second statment which is twice as fast as the first one:
> ------------
> try:
> ergfield.index(ergline)
> except:
> ergfield.append(ergline)
> ------------
> execution time is about 21 seconds
>
> I don't like the second solution because it uses the exeption handling like
> a if statement!
> Are there better ways to do this?
not sure if this is what you want but use a dictionary instead
earlier:
ergDict = {}
if not ergDict.has_key(ergLine):
ergDict[ergLine] = 1
else:
ergDict[ergLine] += 1
later ergDict.keys() is the same as your ergfield
and ergDict.values() (or ergDict.items() with key and value)
contains the number of duplicates
this is only faster if your files contain many different lines
>
> best regards
> werner
>
> BTW: how can I convert an integer to a string?
str(number)
or
"%i" % (number,)
> --
> werner.ho at gmx.de
regards
uwe
More information about the Python-list
mailing list