首页 文章

如何使用def从文件中读取和打印信息? [关闭]

提问于
浏览
-1

我需要一个程序来读取.txt文件中的信息,该文件包含一个人的姓名和他/她的年龄 . 诀窍是 there can be any amount of names and ages ,但他们也可以 repeat but count as one person .

所以.txt文件可以是随机的,但是遵循Name1 Age1的平台:

Sarah 18
Joshua 17
Michael 38
Tom 18
Sarah 18
Michael 38

必须告诉Python将最年轻和最年长的人打印成 new .txt 文件?

我猜测新文件中的打印应该如下所示:

Joshua 17
Michael 38

但我真的不知道如何开始 .

当我开始编码时,我希望我是对的:

info = open("info.txt", "r")

list = info.read()
print (list)

info.close()

但我不知道如何用def确定最年长和最年轻的人 . 任何可以让我走上正轨的提示或建议?

3 回答

  • 3

    在这里使用Dictionary会很好:

    my_dict = {}
    with open('your_file') as f:
        for x in f:
            name, age = x.strip().split()
            my_dict[name] = age
    print max(my_dict.items(), key=lambda x:x[1])
    print min(my_dict.items(), key=lambda x:x[1])
    
  • 1

    你走在正确的轨道上 . 我建议使用以下代码,但我会将写入文件部分告诉您:

    def parse_info(): #If you need, the function can be wrapped up in a function like this. 
        #Notice that you can edit and pass info via arguments, like filename for example
        info = open("info.txt", "r")
        max_age = 0
        max_name = ''
        min_age = float('inf') #sentinel just for the comparison
        min_name = ''
    
        for line in info:
            m_list = line.split(" ") #Represents 'Sarah 18' as ['Sarah', '18'] 
            if int(m_list[1]) > max_age: #Compares if you have found an age higher than any other already found
                max_age = int(m_list[1])
                max_name = m_list[0]
            elif int(m_list[1]) < min_age: #Compares if you have found an age lower than any other already found
                min_age = int(m_list[1])
                min_name = m_list[0]
    
        print ('Max age: ', max_name, ' ', max_age)
        print ('Min age: ', min_name, ' ', min_age)
    
        info.close()
    
  • 0
    file = open("sort_text.txt")
    columnAge = []
    for line in file:
        columnAge.append(line.split(" ")[1].strip() + " " + line.split(" ")[0].strip())
    columnAge.sort()
    print(columnAge[0].split(" ")[1] + " " + columnAge[0].split(" ")[0])
    columnAge.sort(reverse=True)
    print(columnAge[0].split(" ")[1] + " " + columnAge[0].split(" ")[0])
    file.close()
    

    输出:

    Joshua 17
    Michael 38
    

    参考文献:

    list_sort
    string_split

相关问题