【问题标题】:Sorting a CSV file numerically对 CSV 文件进行数字排序
【发布时间】:2018-12-17 05:33:37
【问题描述】:

有什么方法可以将 CSV 文件按降序排序。

我有一个 CSV 文件,其中包含不同玩家的所有分数。下面的代码从 csv 文件中提取前 5 个分数并将其输出到我的程序中。但是我希望输出最高的 5 分,而不是前 5 分。无论如何我可以做到这一点。

   def DisplayLeaderBoard():        
        count = 0
        with open ('StudentNames&Questions.csv') as scorelist:
            reader = csv.DictReader(scorelist)

            for row in reader:
                if count ==250:
                    break
                count = count+50
                scores_label = Label(canvas, text=(row['Names'], row['Score']), bg = 'gray25', fg='snow', font = font1)
                canvas_scores_label = canvas.create_window(350, 280+count, window = scores_label, width = 500, height = 40)

我玩过下面的这段代码,但这主要用于数组。因此,如果有人知道如何先将其放入数组中,然后放入标签的 for 循环中,请告诉我。

        array.sort(key=lambda x: x[0], reverse=True)

【问题讨论】:

  • x[0] 在这里不起作用,因为您已经通过了DictReader。传递 Reader 并在排序键中转换为整数。

标签: python csv sorting


【解决方案1】:

x[0] 在这里不起作用,因为你传递了一个DictReader,所以x 的参数需要是一个列键,而且csv 模块不会将数值转换回整数,因此您最终可以对整数作为字符串的值进行字母排序。

总结一下,需要根据“Score”列的数值进行排序:

for row in sorted(reader,key = lambda x : int(x['Score']),reverse=True):

【讨论】:

    猜你喜欢
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 2015-06-13
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    相关资源
    最近更新 更多