私はライブラリのスクリプトを作成しています。このスクリプトは、著者を平均評価の降順で並べ替えます。
以下は私のリストです:(著者名+ <スペース> +平均評価があります)
['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']
以下は私が試したものです:(値をスペースで分割し、新しいリストに追加してから、3番目の値(評価)で並べ替えました。
for line in rate_order:
sort_list.append(line.split(' '))
print sorted(sort_list, key=itemgetter(2))
問題は、一部の作成者名の名前に3つのスペースが含まれているため、3番目の値が評価ではないことです。より良い(またはよりクリーンな)方法はありますか?
使用する 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)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加