按字母顺序按记录排序数组?

时间:2016-03-01 17:56:13

标签: python arrays sorting alphabetical

我想在数学测验中对数组进行排序,以便对A-Z中的名称进行排序,但我做了很多研究,但却无法找到方法。其他正在执行相同任务的人在代码的末尾使用大约一行或两行。

不要生我的气这是我的第一个问题,我不是最好的,因为我已经离开它很长一段时间做其他课程和任务。

我的代码布局示例:

#Highest to Lowest
if format_choice == "A":
        scores = {}
        with open("classA.txt","r") as result_f:
            for line in result_f:
                (name, secondname, score) = line.split()
                scores[score] = name
        result_f.close()

这可以通过获取文件中的最高分并将其打印到shell中来实现。

如果这不是足够的信息,如果人们想要了解更多信息,我可以展示更多信息。

谢谢。

1 个答案:

答案 0 :(得分:0)

一些仓促的代码,但这应该有效:

#Highest to Lowest
if format_choice == "A":
    with open("classA.txt","r") as result_f:
        scores = []
        for line in result_f:
            [name, secondname, score] = line.split()
            record = [name, secondname, score] # We make a list called "record" With name as its first record
            scores.append(record) # We stick that list onto scores each time
        scores = sorted(scores, key=lambda File: File[0])
    # This is difficult to describe, but this sorts all the lists by their first record, File[0] or names,
    result_f.close()

    print(scores)
    # This prints [['eric', 'ericlastname', '98'], ['fred', 'fredlastname', '2'], ['steve', 'stevelastname', '1']]

在文本文件中,它是:

steve stevelastname 1
fred fredlastname 2
eric ericlastname 98

我还将您的scores = {}更改为scores = [],因为您需要一个数组,而不是字典。