如何使用def?

时间:2015-05-04 17:06:03

标签: python function

我需要一个程序来读取.txt文件中的信息,该文件包含一个人的姓名和他/她的年龄。诀窍是 可以有任意数量的名称和年龄 ,但他们也可以 重复,但算作一个人

因此.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 个答案:

答案 0 :(得分:3)

在这里使用词典会很好:

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 :(得分: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()

答案 2 :(得分: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