user16612111
user16612111

Reputation:

How to sort sublists within a list according to specific attribute in python

I have a list in python that looks like below

a=[['David','McConor','123000','900']
['Timothy','Gerrard','123001','901']]

I desire to sort the list above using the last entry of each sublist as the key. I have succesfully sorted the list lexicographically using the a.sort() function. Now i want to sort the list and print each sublist such that the list with '901' comes first is my problem.

What I tried

##defining what mykey is where am stuck
mykey=
##the sort function has overloads for key
a.sort(key=mykey,reverse=True)

Thanks for your contribution.

Upvotes: 0

Views: 41

Answers (2)

Dejene T.
Dejene T.

Reputation: 989

You can use an alternative way

sorted(a, key = lambda x: (x[-1]), reverse=True)

Upvotes: 0

Pedro Maia
Pedro Maia

Reputation: 2722

key expects a function, you can create a simple lambda function to check for the last item:

a.sort(key=lambda x: x[-1],reverse=True)

Upvotes: 0

Related Questions