来自文本文件的Python最大值

时间:2016-11-20 22:10:35

标签: python python-3.x

我正在尝试从包含数字的文本文件中计算最大值/分钟,但无法弄清楚如何。我能够计算和总数,但不是最大/分钟。任何帮助将非常感激。谢谢!

def main():
    counter = 0
    total = 0
    inputFile = open('Numbers.txt', 'r')

    for numbers in inputFile:
        numbers = float(numbers.rstrip())

        total += numbers
        counter += 1   

    print('Count:', counter)
    print('Total:', total)
    print('Average:', total / counter)

    inputFile.close()

main()

2 个答案:

答案 0 :(得分:3)

实现目标的更简单方法是:

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)

如果您想在代码中执行此操作,可以执行以下操作:

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

答案 1 :(得分:0)

如果您正在处理数字,我建议您使用numpy模块。有了它,您可以非常快速地实现您想要的 - 取决于您的输入文件:

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))

以及更多......如果您的输入文件不易阅读,您可以尝试使用np.genfromtxt来提取数据。