组织和排序文本文件中的数据

时间:2015-11-16 23:13:20

标签: python text-files nested-lists

我根据参加考试的人和他们收到的分数,将一些信息存储在文本文件中。每次他们再次参加考试时,都会增加一个新分数。文本文件看起来像这样,数据存储在其中:

Mike 5 7 9
Terry 6 6 9
Paul 4 5 6

我希望能够从文本文件中检索信息,并确定每个人的最高分,以便打印出他们的姓名和单个号码。

如果我从文件中检索数据并使用以下代码将其存储为列表:

with open("classa.txt") as f:
   content = f.readlines()
   print(content)

然后打印出来的数据如下: ['Mike 5 7 9\n', 'Terry 6 6 9\n', 'Paul 4 5 6']

我猜我真的需要在列表中创建几个嵌套列表。每个人一个,但我不确定如何完成此操作或如何解析数据,以便我可以在列中使用它并忽略"名称"处理其后面的数值时的列。

如果文本文件中的数据以逗号分隔,那么它是否会更好,如下所示:

Mike,5,7,9
Terry,6,6,9
Paul,4,5,6

任何帮助将不胜感激。我有点超出我的深度。

1 个答案:

答案 0 :(得分:2)

with open("names.txt") as f:
    # splitlines of the content
    content = f.read().splitlines()
    for line in content:
        # split at spaces
        splittedLine = line.split(" ")

        # get the first element which is the name
        name = splittedLine[0]

        # get the all the elements except the first
        scores = splittedLine[1:]

        # get the last element of the sorted list which is the highscore
        highscore = sorted(scores)[-1]
        print("{} : {}".format(name, highscore))

我对代码进行了评论,所以我希望一切都可以理解。

输出:

  迈克:9

     特里:9

     保罗:6

相关问题