Python程序,它读取文件,然后计算sum、average、min、max,如果文件中只有一个数字或是空的,则给出消息

2024-04-26 10:35:44 发布

您现在位置:Python中文网/ 问答频道 /正文

def main():
    filename = input("Enter a file name: ")
    with open(filename) as f:
        data = [int(line) for line in f]
        if len(data) > 2:
            print('The smallest number in the file is: ', + min(data))
            print('The largest number in the file is: ', "{:,}".format(+ max(data)))
            print('The total sum of the number in the file is: ', "{:,}".format(sum(data)))
            print('The average from the numbers in the file is: ', "{:,.2f}".format(sum(data)/len(data)))
        elif len(data) == 1:
            print ('There is only one number in your file to process.')
        else:
            print('There are no numbers in your file to process.')         
        f.close()

main()

Tags: theinformatnumberdatalenismain
1条回答
网友
1楼 · 发布于 2024-04-26 10:35:44

根据您的评论,我认为问题出在您的数据上,要解决这个问题,您可以使用以下方法:

lines = filter(None, (line.strip() for line in f))
data = [int(line) for line in lines if line.isnumeric()]

请注意,这只解决了您得到的异常-我没有检查代码的其余部分并验证逻辑

相关问题 更多 >