Python max value from a text file

后端 未结 2 1587
后悔当初
后悔当初 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
    
    0 讨论(0)
  • 2021-01-23 11:41

    If you're working with numbers, I'd suggest using the numpy module. With it, you can achieve what you want very quickly - depending on your input file:

    import numpy as np
    x = np.loadtxt("Numbers.txt")
    print('Total:', np.sum(x))
    print('Average:', np.average(x))
    print('Max:', np.amax(x))
    print('Min:', np.amin(x))
    

    and much more... if your input file isn't as simple to read, you can try using np.genfromtxt to extract the data.

    0 讨论(0)
提交回复
热议问题