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')]
You can use lambda for that:
a = [('1253', 'Fred'), ('1389', 'Sally'), ('889', 'Sue')]
b = sorted(a, key=lambda a: int(a[0]))
>>> 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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With