【发布时间】:2021-11-14 19:10:50
【问题描述】:
我有一个名为 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]))?
标签: python arrays sorting record