从文本文件中找到最小值和最大值 - Python

时间:2015-02-19 22:33:57

标签: python

我需要从此数据列表中找到最小值和最大值。我可以获得最大但最小的。文本文件包含大量数据,因此我决定将其上传到此处: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" )

1 个答案:

答案 0 :(得分:2)

列表理解是你的朋友。

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)