The problem with your method is that x[3] is a string, so it does not make sense to do -x[3].
I am not sure there isn't a simpler solution, but you can use cmp_to_key, and define your own reversed key function:
from functools import cmp_to_key
l = [['hasan', 6, 'bad', 'chennai'],
['vishnu', 7, 'good', 'chennai'],
['tabraiz', 8, 'good', 'bangalore'],
['shaik', 5, 'excellent', 'chennai'],
['mani', 6, 'avarage', 'kerala'],
['cilvin', 9, 'excellent', 'chennai']]
rev_key = cmp_to_key(lambda x,y: 1 if x<y else -1 if x>y else 0)
l.sort(key=lambda x: (rev_key(x[3]), x[2], x[1]))
print(l)
Result:
[['mani', 6, 'avarage', 'kerala'],
['hasan', 6, 'bad', 'chennai'],
['shaik', 5, 'excellent', 'chennai'],
['cilvin', 9, 'excellent', 'chennai'],
['vishnu', 7, 'good', 'chennai'],
['tabraiz', 8, 'good', 'bangalore']]
Note that if you're using Python 2, you can just write:
rev_key = cmp_to_key(lambda x,y: cmp(y,x))
If you didn't want to sort according to several keys, the right way to go would be to use the reverse argument:
>>> sorted(l, key=lambda x: x[3], reverse=True)
[['mani', 6, 'avarage', 'kerala'],
['hasan', 6, 'bad', 'chennai'],
['vishnu', 7, 'good', 'chennai'],
['shaik', 5, 'excellent', 'chennai'],
['cilvin', 9, 'excellent', 'chennai'],
['tabraiz', 8, 'good', 'bangalore']]
These all are working.I do doubt that. Please double check it. To be specific, onlylist.sort(key=lambda x: (x[2], x[0], -x[1]))shall work. Also don't override built-in identifiers likelist.x[3]in decreasing order, then byx[2]in increasing order and then byx[1]in increasing order?