Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Python Sorting problem!

Status
Not open for further replies.

tmakila

Technical User
Dec 20, 2004
1
FI
Hello,

I'm quite a newbie with Python and I ran into a bit of a problemwith sorting a list by more than one field.

I have a list similar to this:
[['10', 'a', 'Something'], ['1', 'a', 'Nothing'],
['3', 'a', 'Anything'], ['10', 'b', 'Something'],
['1', 'b', 'Nothing'], ['3', 'b', 'Anything'],
['10', 'c', 'Something'], ['1', 'c', 'Nothing'],
['3', 'c', 'Anything']]

What I want to do is produce a list containing the same
information in a following order:
1 a Something
3 a Anything
10 a Nothing
1 b Something
3 b Anything
10 b Nothing
1 c Something
3 c Anything
10 c Nothing

The idea is to sort the second fields in the list alphabetically and after that sort them numerically (according to the first field). The third field is irrelevant.

I currently have a def that looks like this:
def sort_by_bar(a, b):
return cmp(a[1], b[1])

(and it gets called by 'list.sort(sort_by_bar)' elsewhere)

This sorts the list by one bar only..

How can I make the def sort it like I described earlier?

Thank you!
 
You need to do something like:
Code:
def sort_by_bar(a, b):
  if a[1] == b[1]:
    return cmp( a[0], b[0] )
  else:
    return cmp( a[1], b[1] )
 
This seems to work as well:
Code:
def sort_by_bar(a, b):
    return cmp(a[1], b[1]) or cmp(a[0], b[0])


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top