python - 如何将记录数组按降序排序
问题描述
我有一个名为 sample.csv 的 csv 文件,我已将其转换为记录,该记录设置有一个字符串值和一个整数值,如下所示:
[Name,10]
[Name1,12]
[Name2,14]
我希望能够将这些记录按降序排序,然后最终打印三个得分最高的学生的姓名和分数以及得分最低的学生的姓名和分数。这是我到目前为止的代码,我无法按整数值对记录进行排序。
import csv
file = open("sample.csv")
csvreader = csv.reader(file)
rows = []
for row in csvreader:
rows.append(row)
file.close()
sortedFile=[]
sortedFile=sorted(rows, key=lambda rows: rows[1])
print(sortedFile)
编辑:
一个非常有帮助的人发表了评论,但现在无论他们删除了他们的评论。
import csv
file = open("sample.csv")
csvreader = csv.reader(file)
rows = []
for row in csvreader:
rows.append(row)
file.close()
sortedFile=[]
sortedFile=sorted(rows, key=lambda rows: int(rows[1]))[::-1]
print(sortedFile[0])
print(sortedFile[1])
print(sortedFile[2])
print(sortedFile[-1])
我的代码现在看起来像这样,我快完成了,我相信我错过了一些非常简单的东西,我想要的只是数组附近的一些文本说
"The person with the highest score is", (name[0]),"with a score of,(score[0])
"The person with the highest score is", (name[1]),"with a score of,(score[1])
"The person with the highest score is", (name[2]),"with a score of,(score[2])
"The person with the lowest score is", (name[-1]),"with a score of,(score[-1])
解决方案
也许是这样的:
sortedFile = sorted(rows, key=lambda rows: int(rows[1]))?
推荐阅读
- asp.net - ASP.NET Core 3.1 HTTP post [FromBody] 总是收到 null
- pandas - Pandas read_csv 在 gzipped 文件上失败并出现 OSError: Not a gzipped file (b'NU')
- javascript - 下拉菜单在第二页上不起作用
- python - 使用简单的 django 项目设置 gitlab CI
- python - 如何将存储在文件夹中的多个json文件读入Python中的不同字典?
- php - 从函数返回的 $stmt 与函数内部不同
- html - 为什么等待 page.Evaluate() 返回“未定义”?
- python-3.x - 从字符串中过滤用户名
- asp.net - IIS:无法识别的属性“runallmanagedmodulesforallrequests”
- excel - VBA 函数作为宏运行,但在使用函数调用时会出错