当有最小值和最大值时,用函数in.txt文件写出结果?

时间:2015-05-19 07:01:02

标签: python max min function

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

程序需要在新的.txt文档中编写最年轻的人,然后是最老的人。

它需要读取的.txt看起来像这样:

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

然后在程序完成后,它应该写入一个新的.txt文件,如下所示:

Joshua 17
Michael 38

到目前为止,我有这个:

def parse_info():
    info = open("info.txt", "r")
    max_age = 0
    max_name = ''
    min_age = float('inf')
    min_name = ''

    for line in info:
        m_list = line.split(" ") 
        if int(m_list[1]) > max_age:
            max_age = int(m_list[1])
            max_name = m_list[0]
        elif int(m_list[1]) < min_age:
            min_age = int(m_list[1])
            min_name = m_list[0]

    info.close()

我不确定如何让程序创建一个新的.txt并写出最年轻和最老的。有什么帮助吗?

3 个答案:

答案 0 :(得分:1)

您可以使用write() method 文件对象将字符串写入文件

var p = Object.create(null);   // p has no prototype
var o = Object.create(p);      // o has p as a prototype
console.log("__proto__" in o); // false, __proto__ comes from Object.prototype, 
                               // which isn't in o's prototype chain

答案 1 :(得分:1)

keyN

应该有效

答案 2 :(得分:0)

通过将集合的属性与元组列表的排序属性相结合,您可以非常轻松地让Python完成所有艰苦的工作。

def parse_info():
    persons = set()
    for line in open('info.txt'):
        name, age = line.split()
        persons.add((int(age), name))   # Note that age comes first

    # At this point, we have removed all duplicates, now we need
    # to extract the minimum and maximum ages; we can simply do
    # this by converting the set to a list and then sort the list.
    # If a list entry is a tuple, the default behaviour is that it
    # sorts by the first entry in the tuple.
    persons = sorted(list(persons))

    # Now write the data to a new file
    fd = open('new_info.txt', 'w')
    age, name = persons[0]
    fd.write('Youngest: %s %d\n' % (name, age))
    age, name = persons[-1]
    fd.write('Oldest: %s %d\n' % (name, age))

parse_info()