problem with custom sort function .... long

Terry Reedy tjreedy at udel.edu
Thu Aug 21 22:14:42 EDT 2003


"Ken R." <kriley1 at hotmail.com> wrote in message
news:1e5ab84a.0308211209.eaf3f22 at posting.google.com...
> Hello all,
> I am relatively new to python but I am having an issue with custom
> sort functions..

Athough they seem to be working fine!

> I am trying to sort a list of lists or tuples with arbitrary
ascending
> or descending sorts. For example given a list of tuples
> ('firstname','lastname','age') I want to be able to sort lastname
> descending, firstname ascending and age ascending...
>
> I wrote a custom function generator to generate a sort function
based
> on an input list of column numbers and sort direction. Sort seems to
> sort the first column ascending regardless of what the sort function
> says. I also googled this group for  other solutions and found a
more
> elegant one than mine but with the same results.

Given that your example data all have 'a' in the first column, these
statements of ill behavior make no sense!

> Here is my code and result:
> sortList = [('2','D'),('1','D'),('0','D')]
> dataList = []
> dataList.append(['a','a','b'])
> dataList.append(['a','a','a'])
> dataList.append(['a','a','c'])
> dataList.append(['a','b','a'])
> dataList.append(['a','b','b'])
> dataList.append(['a','b','c'])
> dataList.append(['a','c','a'])
> dataList.append(['a','c','b'])

You could just as well write dataList as a single literal.

[snip]

> [['a', 'b', 'c'], ['a', 'a', 'c'], ['a', 'c', 'b'], ['a', 'b', 'b'],
> ['a', 'a', 'b'], ['a', 'c', 'a'], ['a', 'b', 'a'], ['a', 'a', 'a']]

and columns 2, 1, and 0 are descending (non-increasing) in that order,
just as you asked.  What different were you expecting given the input.

> and Manuel Garcia's solution and results:
> sortList = [(0,-1),(1,-1),(2,-1)]
...
> Results:
> [['a', 'c', 'b'], ['a', 'c', 'a'], ['a', 'b', 'c'], ['a', 'b', 'b'],
> ['a', 'b', 'a'], ['a', 'a', 'c'], ['a', 'a', 'b'], ['a', 'a', 'a']]

Again, just as requested.  Same question.

> is this an issue with sort or is my code screwy?

Perhaps your understanding of ascending and descending?  or of nested
sorting?

Terry J. Reedy






More information about the Python-list mailing list