通过考虑python中的两个或三个索引来排序列表列表

时间:2014-01-17 09:27:37

标签: python

list = [["hasan",6,"bad","chennai"], ["vishnu",7,"good","chennai"], ["tabraiz",8,"good","bangalore"], ["shaik",5,"excellent","chennai"], ["mani",6,"avarage","kerala"], ["cilvin",9,"excellent","chennai"]]

优先考虑

{'excellent':4, 'good':3, 'average':2, 'bad':1}    

list.sort(key=lambda x: (x[3], -x[2], -x[1]))
list.sort(key=lambda x: (x[2], x[0], -x[1]))
list.sort(key=lambda x: (x[2], -x[3], x[0]))

这些都有效。

但它说

TypeError: bad operand type for unary -: 'str'

当试图在第一个位置放置负号时。

list.sort(key=lambda x: (-x[3], x[2], x[1]))

为什么????

1 个答案:

答案 0 :(得分:1)

您的方法存在的问题是x[3]是一个字符串,因此执行-x[3]没有意义。

我不确定是否有更简单的解决方案,但您可以使用cmp_to_key,并定义自己的反向key功能:

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)

结果:

[['mani', 6, 'avarage', 'kerala'],
 ['hasan', 6, 'bad', 'chennai'],
 ['shaik', 5, 'excellent', 'chennai'],
 ['cilvin', 9, 'excellent', 'chennai'],
 ['vishnu', 7, 'good', 'chennai'],
 ['tabraiz', 8, 'good', 'bangalore']]

请注意,如果您使用的是Python 2,则只需编写:

rev_key = cmp_to_key(lambda x,y: cmp(y,x))

如果您不想根据几个键进行排序,那么正确的方法是使用reverse参数:

>>> 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']]