Sunday, April 17, 2011

case-insensitive alphabetical sorting of nested lists

i'm trying to sort this nested list by inner's list first element:

ak = [ ['a',1],['E',2],['C',13],['A',11],['b',9] ]
ak.sort(cmp=lambda x, y: cmp(x[0], y[0]))
for i in ak: {
 print i
}

by default python considers A > a, hence the output i get is:

['A', 11] ['C', 13] ['E', 2] ['a', 1] ['b', 9]

i've tried converting all list values to even case during comparison by adding x[0].lower etc. but no use. How do i force python (i'm working on 2.4 version) to do case-insensitive alphabetical sorting?

Edited:

Jarret and Brian, your assumptions about parenthesis were right! I did forget to put them in! And Jarret, your suggestions about not using "cmp" works like a charm! Thanks a lot guys!

From stackoverflow
  • Try:

    ak.sort(key=lambda x:x[0].lower())
    

    I would recommend that you avoid using cmp as this has been deprecated in Python 2.6, and removed in 3.0. I know you're using 2.4, but the reason cmp has fallen into disfavour is that it is a very slow way to sort.

    I'm not sure why your effort with lower failed, though... perhaps you forgot to use the function call versus just the function name? (ie: cmp(x[0].lower(), y[0].lower()) versus cmp(x[0].lower, y[0].lower))

  • ak.sort(cmp=lambda x, y: cmp(x[0].lower(), y[0].lower()))
    

    Did you forget the parens in x[0].lower()?

0 comments:

Post a Comment