3

I have a list of tuples, with each tuple containing information about an employee.

EmpList= [('1253', 'Fred'), ('889', 'Sue'), ('1389', 'Sally')]

I'd like to arrange them in increasing order by their employee number. Using sorted, my first inclination, doesn't work since the numbers aren't integers. Hence

sorted(EmpList)
[('1253', 'Fred'), ('1389', 'Sally'), ('889', 'Sue')]

when I'd like

[('889', 'Sue'), ('1253', 'Fred'), ('1389', 'Sally')]
kevin
  • 147
  • 2
  • 11
  • possible duplicate of [How to sort (list/tuple) of lists/tuples?](http://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples) – zs2020 Apr 13 '14 at 03:36

1 Answers1

5

You can use lambda for that:

a = [('1253', 'Fred'), ('1389', 'Sally'), ('889', 'Sue')]
b = sorted(a, key=lambda a: int(a[0]))

Your case

>>> EmpList = [('1253', 'Fred'), ('889', 'Sue'), ('1389', 'Sally')]
>>> b = sorted(a, key=lambda EmpList: int(EmpList[0]))
>>> b
[('889', 'Sue'), ('1253', 'Fred'), ('1389', 'Sally')]

To get reversed values, you can do:

>>> EmpList = [('1253', 'Fred'), ('889', 'Sue'), ('1389', 'Sally')]
>>> b = sorted(a, key=lambda EmpList: int(EmpList[0]), reversed=True)
>>> b
[('1389', 'Sally'), ('1253', 'Fred'), ('889', 'Sue')]

Note

Note the importance of casting the a[0] as an int. This is because if you do not cast it as an int, python will do the comparisons on string and:

>>> '889' > '1253'
True

This is because when python compares the first character of each string, '8' is greater than '1' and therfore, '889' > '1253' evaluates to True.

This is definitely not what you want. So to do it properly, cast it as int.

sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • The ``int`` cast is probably redundant, the string-sort for numbers will be equivalent and the cast is just as expensive as the string comparison. – aruisdante Apr 13 '14 at 03:29
  • @aruisdante, I tried it without the casting and it didn't work. Probably because '889' > '1253' in strings – sshashank124 Apr 13 '14 at 03:31
  • though you could just use the ``reverse`` parameter to get the expected output. – aruisdante Apr 13 '14 at 03:36
  • @aruisdante: that won't suffice. Consider `['2','10','3']`. – DSM Apr 13 '14 at 03:39
  • It might be worth mentioning that the reason `'889 > 1253'` is the first element of `'889'` : `'8'` is greater than first element of `'1253'` : `'1'`. – Akavall Apr 13 '14 at 03:40
  • Yeah, that's weird, python's string comp doesn't do what I thought it did. Seems it only holds true of numbers of equivalent digits. – aruisdante Apr 13 '14 at 03:41
  • @Akavall, Thank you! I have include that in my explanation. – sshashank124 Apr 13 '14 at 03:42
  • Thank you! How might I arrange them in the opposite direction, in descending order? I tired sticking a reverse at the end, to no avail – kevin Apr 13 '14 at 04:15