Improving upon the Decorate-Sort-Undecorate idiom

Paul McGuire ptmcg at austin.rr._bogus_.com
Wed Jun 23 06:06:50 CEST 2004


"Thomas Philips" <tkpmep at hotmail.com> wrote in message
news:b4a8ffb6.0406221212.741d2379 at posting.google.com...
> I recently had the need to sort a large number of lists of lists, and
> wondered if an improvement to the Decorate-Sort-Undecorate idiom is in
> the works. Ideally, I would like to sort the list of lists (or tuples)
> in place by using a simple variant of the current idiom, i.e.
>
> list_of_lists.sort(*columns)
>
> where *columns is a tuple that specifies the column order for the
> sort. If *columns is left blank, the sort ought to work as it does
> today, i.e.
>
> list_of_lists.sort()
>
> should sort by columns 0, 1,2,.....
>
> Has such a method been considered for inclusion in Python? Does it
> have any problems that would inhibit its adoption?
>
> Thomas Philips
Thomas -

Here are some pure-Python ideas, plus a preview of the Python 2.4 sort()
enhancement.

-- Paul


import pprint
listOfLists = [
    [ 'a', 1, 'z', 3.1 ],
    [ 'c', 0, 'z', 4.2 ],
    [ 'a', 1, 'y', 5.5 ],
    [ 'b', 2, 'z', 1.0 ],
    [ 'c', 0, 'z', 4.2 ],
    ]

print "\n- original list"
pprint.pprint (listOfLists)

print "\n- vanilla sort()"
listOfLists.sort()
pprint.pprint (listOfLists)

def byColumns(col):
    def columnCompare(a,b):
        for c in col:
            if a[c] != b[c]:
                return cmp(a[c],b[c])
        else:
            return 0
    return columnCompare

print "\n- using custom sort method"
columns = (1, 2, 0)
listOfLists.sort(byColumns(columns))
pprint.pprint (listOfLists)

def sortByColumns(lst,cols):
    tmp = [ ([item[c] for c in cols],item) for item in lst ]
    tmp.sort()
    return [ t[1] for t in tmp]

print "\n- using D-S-U with varying input columns"
columns = (2,3)
listOfLists = sortByColumns(listOfLists, columns)
pprint.pprint (listOfLists)

print "\n- using key argument in Python 2.4 (compare to D-S-U)"
cols = (1,3)
listOfLists.sort( key=lambda item: [item[c] for c in (cols)] )
pprint.pprint (listOfLists)





More information about the Python-list mailing list