Organising and sorting data from a text file

白昼怎懂夜的黑 提交于 2019-12-25 03:49:29

问题


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

I'd like to be able to retrieve the information from the text file and identify the highest score for each person so that it printed out their name and a single number.

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)

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.


回答1:


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.

Output:

Mike : 9

Terry : 9

Paul : 6



来源:https://stackoverflow.com/questions/33746400/organising-and-sorting-data-from-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!