Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

python - How to find the average of values in a .txt file

I need to find the minimum, maximum, and average of values given in a .txt file. I've been able to find the minimum and maximum values but I'm struggling with finding the average of values. I haven't wrote any coding for determining the average as I have no clue where to start. My current code is:

def summaryStats():
    filename = input("Enter a file name: ")
    file = open(filename)
    data = file.readlines()
    data = data[0:]
    print("The minimum value is " + min(data))
    print("The maximum value is " + max(data))

I need to be able to return the average of these values. As of now the .txt document has the following values:

893
255
504

I'm struggling on being able to find the average of these because every way I try to find the sum my result is 0.

Thanks (sorry I'm just learning to work with files)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should convert the data retrived from file to integers first, because your data list contains strings not numbers. And after the conversion to integers average can be found easily:

Why conversion to int is required?

>>> '2' > '10'  #strings are compared lexicographically
True

Code:

def summaryStats():
    filename = input("Enter a file name: ")
    with open(filename) as f:
        data = [int(line) for line in f]

    print("The minimum value is ", min(data))
    print("The maximum value is ", max(data))
    print("The average value is ", sum(data)/len(data))

Output:

Enter a file name: abc1
The minimum value is  255
The maximum value is  893
The average value is  550.6666666666666

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...