5
$\begingroup$

I have a list of employee records. Each tuple of the list represent a person's record, which includes his name, ID, and age.

For example,

emp_records = [('Karim',100, 45), ('Rahim',10, 30),('Salim', 300,60),('Abu',50,35)]

Now, I want to sort emp_records based on ID.

$\endgroup$
6
$\begingroup$

You can use lambda function to pass argument by which you need to sort the records.

For example,

sorted_list=sorted(emp_records, key=lambda emp : emp[1])   //Here 1 means ID    
print(sorted_list)

You can also use the operator module. The operator module has the itemgetter function, which takes item as argument and sort based on the argument

For example,

from operator import itemgetter    
sorted_list=sorted(emp_records, key=itemgetter(1)) // Here 1 means ID    
print(sorted_list)
| improve this answer | |
$\endgroup$
2
$\begingroup$

Use the sorted function. It accepts key as argument.
You can then use a lambda to sort on the relevant index of your tuple.

sorted(emp_records, key=lambda x: x[1])
| improve this answer | |
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.