组织和排序文本文件中的数据 [英] Organising and sorting data from a text file

查看:63
本文介绍了组织和排序文本文件中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经根据参加考试的人及其获得的分数将一些信息存储在文本文件中.每次他们再次参加考试时,都会添加一个新分数.文本文件如下所示,其中存储了数据:

I've got some information stored in a text file based on people taking a test and the scores they have received. Every time they take the test again, a new score is added. The text file looks like this with the data stored within it:

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

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

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

If I retrieve the data from the file and store it as a list using this code:

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']

then the data is printed out like this: ['Mike 5 7 9\n', 'Terry 6 6 9\n', 'Paul 4 5 6']

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

I'm guessing that I really need to create several nested lists within a list. One for each person but i'm unsure how to accomplish this or how to parse the data so that I can work with it in columns and ignore the "Name" column when dealing with the numeric values that follow it.

最好用逗号分隔文本文件中的数据,使其看起来像这样:

Would it be better if the data in the text file was comma delimited so that it read like this:

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

任何帮助将不胜感激.我对此有点不了解.

Any help would be appreciated. I'm a little out of my depth with it.

推荐答案

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))

我注释了代码,希望所有内容都是可以理解的.

I commented the code so i hope everything is understandable.

输出:

迈克:9

Mike : 9

特里:9

保罗:6

这篇关于组织和排序文本文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆