[英]How to do a numeric reverse sort in python on a list which contains numbers and letters
我的清單是這樣的:
10.987|first sentence
13.87|second sentence
9.098|third sentence
如果我做類似的事情:
for x in my_list:
sorted(my_list, reverse=True)
我從邏輯上得到:
9.098|third sentence
13.87|second sentence
10.987|first sentence
這是因為它沒有被解釋為數字,但是我無法將整個字符串轉換為浮點數。 我想要的是第一部分的數字排序:
13.87|second sentence
10.987|first sentence
9.098|third sentence
我嘗試使用itemgetter,但似乎找不到我想要的東西。 在bash中可以輕松解決
sort -k
在python中有等效的工具嗎?
這是一種方法。
lst = ['10.987|first sentence',
'13.87|second sentence',
'9.098|third sentence']
res = sorted(lst, key=lambda x: -float(x.split('|')[0]))
結果
['13.87|second sentence',
'10.987|first sentence',
'9.098|third sentence']
說明
sorted
使用參數key
,可讓您指定要進行排序的自定義( lambda
)函數。 lambda
函數以“ |”分隔 並提取第一部分以獲取數字分量。 float
並最終求反以確保降序。 reverse=True
參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.