首页 > 解决方案 > 如何根据从python中的字符串中提取的数值按降序对记录进行排序?

问题描述

I have a data set like this: 

在此处输入图像描述

 Surface Book 2 Review: How Microsoft Won My Five Stars At The Edinburgh Fringe | 0.5047957
 Remove the Power PC Care 2018 PUP | 0.44716716
 9 Months of Xbox Live (New or Returning Only, otherwise 7 months for $21) $23 | 0.42284298
 US probe into Microsoft software sales in Hungary | 0.42226338

我正在尝试根据|符号后存在的值对数据进行排序。所以基本上我想根据哪个具有最高值来显示整个字符串并获得前 10 名。

 I tried doing this but I cannot figure out how to order by only that numerical value. 

 listnew = sorted(Calculatedvalues, key = lambda x : x[1], reverse = True)[:10]
 for item in listnew:
                 print (item)

我的输出是这样的:

38 What is Thinking? #Intelligence | 0.15786803
38 What is Thinking? #Intelligence | 0.15786803
8.31 PF | 0.02431465
️ Hop on, Jerry. Here are 50 points. | 0.25864878

如果我们看到这些分数基本上低于数据集中存在的分数,我理解这不是正确的方法,我无法找到仅基于特定部分的排序方法。

我提到了这些问题中提供的答案,但没有帮助。

对前十名结果进行排序

从下面提供的答案之一:我尝试使用提到的这种方法

Calculatedvalues.sort(key = lambda x: x.split("(")[1]))

但我收到此错误

list index out of range

按字符串的一部分对字符串列表进行排序

标签: pythonpython-3.x

解决方案


你很接近,但你从来没有真正分割你的行|,你需要使用split将每一行转换为列表,然后根据列表的第二项对其进行排序,

请试试这个,

listnew = sorted(Calculatedvalues, key = lambda x: float(x.split("|")[-1]), reverse=True)[:10]
# output,
# ['Surface Book 2 Review: How Microsoft Won My Five Stars At The Edinburgh Fringe | 0.5047957\n', 'Remove the Power PC Care 2018 PUP | 0.44716716\n', '9 Months of Xbox Live (New or Returning Only, otherwise 7 months for $21) $23 | 0.42284298\n', 'US probe into Microsoft software sales in Hungary | 0.42226338']

推荐阅读