Python max value from a text file

后端 未结 2 1588
后悔当初
后悔当初 2021-01-23 10:53

I\'m trying to calculate max/min from a text file containing numbers, but can\'t figure out how. I was able to do count and total, but not max/min. Any help would be much apprec

2条回答
  •  一个人的身影
    2021-01-23 11:40

    Simpler way to achieve what you are doing is:

    num_list = [float(num) for num in inputFile.read().split())
    # OR, num_list = map(float, inputFile.read().split())
    
    counter = len(num_list)
    total = sum(num_list)
    
    # Your desired values
    max_val = max(num_list)
    min_val = min(num_list)
    

    In case you want to do it in your code, you may do:

    min_value, max_value = 999, -999  # Range based on the value you are sure you data will lie within
    
    for numbers in inputFile:
        numbers = float(numbers.rstrip())
        # ... your other logic
        if min_val > numbers:
            min_val = numbers
        if max_value < numbers:
            numbers = numbers
    

提交回复
热议问题