Python max value from a text file

后端 未结 2 1604
后悔当初
后悔当初 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: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.

提交回复
热议问题