【问题标题】:Organising and sorting data from a text file从文本文件中组织和排序数据
【发布时间】:2015-11-16 23:13:19
【问题描述】:

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

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

任何帮助将不胜感激。我对它有点不知所措。

【问题讨论】:

    标签: python text-files nested-lists


    【解决方案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))
    

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

    输出:

    迈克:9

    特里:9

    保罗:6

    【讨论】:

    • 那太好了。非常感谢。早上回到电脑前,我会先尝试一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    相关资源
    最近更新 更多