python - 如何根据从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
解决方案
你很接近,但你从来没有真正分割你的行|
,你需要使用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']
推荐阅读
- python - 选择存储在变量中的 DF 行。如何仅对这些行进行操作?
- r - 循环 PDF 以创建数据框
- msbuild - 我怎样才能摆脱神秘的警告:“'../project.csprojAssemblyReference.cache'已经存在”?
- mysql - Spring JPA 无法更新名称包含连字符的 MySQL 数据库
- sql - SQL Server - 启用代理而不删除和重新创建它
- python - Django:未找到反向 URL 模式
- java - 对象的数组列表
- jquery - 强制对子 div 进行内部换行
- xamarin.forms - Xamarin Forms,在棱镜中设置 BarBackgroundColor NavigationPage
- javascript - 拖放和 ol.interactionSelect 上的 kml 样式