簡體   English   中英

從文本文件中查找最小和最大-Python

[英]Find Min and Max from Text File - 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" )

列表理解是您的朋友。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM