Python读写txt文件时get_min函数报错‘l不可读’求助
修正最小值计算函数的报错问题
你的代码中get_min函数报错的核心原因是:函数定义时声明接收参数l,但函数内部却试图调用外部的nums变量——这个变量仅存在于循环的作用域内,函数内部无法访问,因此抛出了找不到变量的错误。
修正方案
只需要将get_min函数内的nums替换为参数l,和get_max、get_avg保持一致的参数使用逻辑即可:
in_file = open("input.txt", "r") out_file = open("output.txt", "w") def get_min(l): return min(l) # 将原代码的nums改为函数参数l def get_max(l): return max(l) def get_avg(l): return sum(l) / len(l) for line in in_file: parts = line.split(":") cmd = parts[0].strip().lower() nums = parts[1].strip().split(",") for i in range(len(nums)): nums[i] = int(nums[i]) if cmd == "min": out_file.write("The min of [" + ", ".join([str(i) for i in nums]) + "] is " + str(get_min(nums)) + "\n") elif cmd == "max": out_file.write("The max of [" + ", ".join([str(i) for i in nums]) + "] is " + str(get_max(nums)) + "\n") elif cmd == "avg": out_file.write("The avg of [" + ", ".join([str(i) for i in nums]) + "] is " + str(get_avg(nums)) + "\n") # 补充换行符,保持输出格式统一 in_file.close() out_file.close()
额外优化建议
可以使用Python的with语句管理文件操作,它会自动处理文件的关闭逻辑,避免手动关闭可能出现的遗漏:
def get_min(l): return min(l) def get_max(l): return max(l) def get_avg(l): return sum(l) / len(l) with open("input.txt", "r") as in_file, open("output.txt", "w") as out_file: for line in in_file: parts = line.split(":") cmd = parts[0].strip().lower() nums = list(map(int, parts[1].strip().split(","))) # 用map简化类型转换 if cmd == "min": out_file.write(f"The min of [{', '.join(map(str, nums))}] is {get_min(nums)}.\n") elif cmd == "max": out_file.write(f"The max of [{', '.join(map(str, nums))}] is {get_max(nums)}.\n") elif cmd == "avg": out_file.write(f"The avg of [{', '.join(map(str, nums))}] is {get_avg(nums)}.\n")
内容的提问来源于stack exchange,提问作者Miwok
相关产品推荐
相关产品推荐

