根据不均匀的值排序列表

时间:2016-08-30 12:18:47

标签: python python-2.7

我正在为一个库创建一个脚本,它按照Avg评级的降序对作者进行排序。

以下是我的清单:(作者姓名+< space> +平均评分)

['Michael Crichton 4.71', 'J.K. Rowling 4.36', 'Sidney Sheldon 4.63', 'Narendra Kohli 4.9', 'Jeffrey Archer 4.62', 'Devdutt Pattanaik 4.42', 'George R.R. Martin 5.0', 'Dan Brown 5.0', 'Katherine Applegate 3.0', 'Eoin Colfer 4.25', 'Arthur Conan Doyle 5.0', 'Clive Cussler 4.66', 'Stephen King 3.66', 'Douglas Preston 5.0']

下面是我尝试的内容:(我用空格分割值,并附加在新列表中,然后用第三个值排序,即评级。

for line in rate_order:
    sort_list.append(line.split(' '))
print sorted(sort_list, key=itemgetter(2))

问题是某些作者姓名的名称中有三个空格,因此第三个值未评级。可以有更好(或更清洁)的方式吗?

4 个答案:

答案 0 :(得分:3)

您可以在空格处拆分,然后获取最后一个组件的浮点值。以下是整个事情:

>>> print sorted(rate_order, key=lambda r:float(r.split(' ')[-1]))
['Katherine Applegate 3.0', 'Stephen King 3.66', 'Eoin Colfer 4.25', 'J.K. Rowling 4.36', 'Devdutt Pattanaik 4.42', 'Jeffrey Archer 4.62', 'Sidney Sheldon 4.63', 'Clive Cussler 4.66', 'Michael Crichton 4.71', 'Narendra Kohli 4.9', 'George R.R. Martin 5.0', 'Dan Brown 5.0', 'Arthur Conan Doyle 5.0', 'Douglas Preston 5.0']

请注意,[-1]索引会提取 last 元素(从头开始的第一个)。

答案 1 :(得分:2)

使用rsplit

>>> help(''.rsplit)
Help on built-in function rsplit:

rsplit(...)
    S.rsplit([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string, starting at the end of the string and working
    to the front.  If maxsplit is given, at most maxsplit splits are
    done. If sep is not specified or is None, any whitespace string
    is a separator.

>>> 'George R.R. Martin 5.0'.rsplit(' ', 1)
['George R.R. Martin', '5.0']

获取分割的最后一项的另一种方法是使用索引-1:

>>> 'George R.R. Martin 5.0'.split()[-1]
'5.0'

如果您的列表名为author_ratings,则可以通过执行

对其进行排序
author_ratings.sort(key=(lambda(s): float(s.rsplit(' ', 1)[1])), reverse=True)

答案 2 :(得分:1)

rate_order=['Michael Crichton 4.71', 'J.K. Rowling 4.36', 'Sidney Sheldon 4.63', 'Narendra Kohli 4.9', 'Jeffrey Archer 4.62', 'Devdutt Pattanaik 4.42', 'George R.R. Martin 5.0', 'Dan Brown 5.0', 'Katherine Applegate 3.0', 'Eoin Colfer 4.25', 'Arthur Conan Doyle 5.0', 'Clive Cussler 4.66', 'Stephen King 3.66', 'Douglas Preston 5.0']
sort_list=[]
for line in rate_order:
    sort_list.append(line.split(' '))

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

答案 3 :(得分:0)

您可以在sorted函数中使用正则表达式(regular expressions)匹配。使用这种搜索方法,您可以找到与其在字符串中的位置无关的评级。

import re
print sorted(sort_list, key=lambda el: re.search(r'\d\.\d+', el).group(0))

在此代码中,我们使用regex built-in library按模式\d.\d+搜索。

其中:

  

\d - 匹配任何数字字符(相当于[0-9]

     

\. - 匹配点本身

     

\d+ - 匹配一个或多个数字字符

另外,.group(0) method我们正在通过正则表达式搜索结果。

lambda函数来自functional programming,我们将el参数传递给它,这与您排序时的每个元素相对应。