【问题标题】:Find Min and Max from Text File - Python从文本文件中查找最小值和最大值 - Python
【发布时间】:2015-02-19 22:33:57
【问题描述】:

我需要从这个数据列表中找到最小值和最大值。我可以得到最大值但最小值。文本文件有很多数据所以我决定在这里上传:https://www.dropbox.com/s/u5ov5zij9v5fumt/project05.data.txt?dl=0

输入

try:
    file_name = input("Enter the name of an input file ")
    input_file = open( file_name, "r" )
    header=input_file.readline()
    count=0
    total=0  
    largest_num=0
    smallest_num=0
    michigan=""
    for line in input_file:
        output=float(line[67:71].rstrip())

        total += output
        count +=1
        if largest_num<= output:
            largest_num = output

        if smallest_num >= output:
            smallest_num = output

        if line[0:17].rstrip() == "Michigan":
            state=(line[0:17])
            number=(line[67:75])
    print("\nState with the smallest MMR vaccation rate:")
    print("   with a rate of")
    print("\n State with largest MMR vaccination rate:" )
    print("   with a rate of")

    print("\nThe calculated average vaccination rate is",round(total/count,1))
    print("")
    print("Michigan MMR vaccination rate is", number)
    input_file.close()
    except FileNotFoundError:
        print("Error: file not found")
        file_name = input("Enter the name of an input file ")
        input_file = open( file_name, "r" )

【问题讨论】:

  • 这与读取和/或写入文件有什么关系?真正的问题是什么?
  • 请尝试修复缩进 :)
  • 试图找出MMR疫苗接种率的最小值和最大值(见txt文件)
  • 你甚至从不打印largest_numsmallest_num;你怎么知道他们没有正确的价值观?
  • 你将smallest_num初始化为0,所以只有负值会改变它。

标签: python


【解决方案1】:

列表推导是你的朋友。

numbers = [float(line[67:71].rstrip()) for line in input_file]

largest_num = max(numbers)
smallest_num = min(numbers)
total = sum(numbers)
count = len(numbers)

【讨论】:

  • 你不需要剥离浮点数来工作它会忽略空格
猜你喜欢
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
  • 1970-01-01
  • 2013-04-19
  • 1970-01-01
  • 2014-07-15
相关资源
最近更新 更多