-1

Possible Duplicate:
Sorting a tuple that contains tuples

I am having some trouble with sorting a tuple which contain number and string. in the beginning, I have a tuple like this:

a=(("a",2),("b",2),("a",1))

then how can I sort it into: (by number first then alphabetical)

a=(("a",1),("a",2),("b",2))

Thank a lot for your help!

Community
  • 1
  • 1
Brian Lin
  • 323
  • 1
  • 4
  • 12

3 Answers3

3

Tuples cannot be sorted by definition because they are immutable. You can convert this to a list, sort the list, and then convert back to tuple. Something like this,

mylist = sorted(a, key = lambda x: str(x[1])+str(x[0]))
a = tuple(mylist)
vasek1
  • 13,541
  • 11
  • 32
  • 36
3
>>> a=(("a",2),("b",2),("a",1))
>>> from operator import itemgetter
>>> sorted(a, key=itemgetter(1, 0))
[('a', 1), ('a', 2), ('b', 2)]
Petr Viktorin
  • 65,510
  • 9
  • 81
  • 81
setrofim
  • 715
  • 3
  • 12
1

The built-in function sorted will do that for you.

Bite code
  • 578,959
  • 113
  • 301
  • 329