Keeping two lists aligned after processing

philly_bob b0bm00r3 at gmail.com
Sun May 11 02:22:43 EDT 2008


"""
I have a population of five algorithms. Each Alg has a method,
Alg.accuracy(), which calculates its accuracy. Running the accuracy
method on each Alg, I end up with a list of accuracies like [0.75,
0.10, 0.45, 0.80, 0.45]

Now I want to store the algorithms and associated accuracies in a
file, in descending order of accuracy.

Here's how I do it now. There must be a better way! This method is
inelegant, and does not handle at all the issue of what to do with
duplicate accuracies, such as the two different algorithms with 0.45
accuracies in the example above. It merely saves the first of the
duplicates -- not what I want at all.

I want to end up with a file:

0 AlgD 0.80
1 AlgA 0.75
2 AlgC 0.45
3 AlgE 0.45
4 AlgB 0.10

"""

algs=['AlgA', 'AlgB', 'AlgC', 'AlgD', 'AlgE']
accs=[]
for alg in algs:
   thisacc=getattr(alg.accuracy)()   #comp.lang.python April
   accs.append(thisacc)

unsortedaccs=[x for x in accs] # to preserve unsorted
accs.sort()
accs.reverse()   # ending up with sorted list

nuorder=[]
for ax,acc in enumerate(accs):
   spot=unsortedaccs.index(acc)
   nuorder.append(spot)

ofn=open('store.alg','w')
for ord in nuorder:
   alg=algs[ord]
   acc=unsortedlist[ord]
   ofn.write("%d %s,%s" % (ord,alg,str(acc))
ofn.close()



More information about the Python-list mailing list