列表python中的字母串联断路器

时间:2013-08-21 10:20:14

标签: python list sorting

我有一个如下所示的列表:

['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']

这些数字代表学生的考试成绩。我想使用sorted()函数对学生排名中的列表进行排序,并且断路器是按字母顺序排列的名称。我对这个功能不太熟悉,所以非常感谢你的帮助! =)

3 个答案:

答案 0 :(得分:1)

key参数与sorted()一起使用,然后添加自己的功能。

>>> L = ['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']
>>> def mysort(x):
...     temp = x.split(',')
...     return (-int(temp[1]), temp[0])
... 
>>> sorted(L, key=mysort)
['Claudia Zingaro,50', 'Ivan Connolly,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']

使用列表中的每个值调用该函数。该函数将返回[46, 'Invalid Name']之类的内容。然后,sorted()看到这个并根据给定的列表对其进行排序,第一个项目具有更高的优先级。

答案 1 :(得分:1)

您可以使用sort(key=...)功能。

试试这个:

L = ['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']
L.sort(key=lambda x:int(x.split(',')[1]))

输出:

['Invalid Name,46', 'Cristi Authement,47', 'Yadira Millwood,47', 'Hyun Castleberry,48', 'Invalid Name,48', 'Floria Rozar,49', 'Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50']

简单明了。

答案 2 :(得分:0)

从:

开始
L = ['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']

要按多个键排序,首先按照您希望的顺序对“辅助”键进行排序,例如,我们将按字母顺序排列,忽略大小写:

L.sort(key=str.lower)

给我们:

['Claudia Zingaro,50', 'Cristi Authement,47', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,46', 'Invalid Name,48', 'Ivan Connolly,50', 'Jeffie Honaker,50', 'Yadira Millwood,47']

然后,我们按降序排序得分字段:

L.sort(key=lambda L: int(L.rpartition(',')[2]), reverse=True)

这给L最终结果:

['Claudia Zingaro,50', 'Ivan Connolly,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']