Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrange a list of tuples by integer

Tags:

python

tuples

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')]
like image 269
kevin Avatar asked Nov 22 '25 11:11

kevin


1 Answers

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.

like image 59
sshashank124 Avatar answered Nov 24 '25 04:11

sshashank124



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!