gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:33:02 28 4
gpt4 key购买 nike

我需要一个程序来从 .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 并写入最年轻和最年长的文件。有帮助吗?

最佳答案

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

with open("new.txt", "w") as output_file:

output_file.write( "{0} {1}\n".format(max_name, max_age) )
output_file.write( "{0} {1}".format(min_name, min_age) )

关于python - 当有最小值和最大值时,用函数in.txt 文件写出结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30318761/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com