簡體   English   中英

如何在包含數字和字母的列表上的python中進行數字反向排序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM