0

我有一个看起来像这样的列表:

['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() 函数在学生排名中对列表进行排序,并且决胜局是按字母顺序排列的名称。我对这个功能不太熟悉,所以非常感谢您的帮助!=)

4

3 回答 3

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()看到这个并根据给定的列表对其进行排序,第一个项目具有更高的优先级。

于 2013-08-21T10:24:04.743 回答
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']

它简单明了。

于 2013-08-21T10:25:57.607 回答
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']

然后,我们对 score 字段进行降序排序:

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']
于 2013-08-21T11:05:48.187 回答