简体   繁体   中英

How do I average a list of integers in a file?

The file that I'm incorporating in my program is filled with a list of numbers. I have to convert that file to an integer to display the average.

import os.path

def main():
    try:
        filename = input("name of the file: ")
        print(os.path.abspath(filename))
    except IOError:
        print("File not found")
    except ValueError:
        print("Cannot convert into an integer")

main()

Some thoughts:

open will get you a file object which is iterable . When you iterate over the file it will yield each line in turn. int is a constructor as well as a type - you can pass it a string and it will return an integer value if the string can be converted to an int .

Finally, you may want to look at the built in function sum which can take an iterable of numbers and return the sum of those numbers.

An example implementation:

from os.path import abspath

def get_file_sums():
    name = input("Please provide a file name:")
    with open(abspath(name), "r", encoding="utf-8") as fo:
        result = sum(int(line, base=10) for line in fo)
        print("The result is:", result)

if __name__ == "__main__":
    get_file_sums()

This should work:

nums = []
with open('nums.txt', 'r') as f:
    for line in f:
        nums.extend([int(x) for x in line.split()])
print sum(nums)/len(nums)

The nums.extend supports files that have multiple numbers per line (that's why it's a little complicated).

def compute_average(path):
    with open(path) as fp:
        values = map(int, fp.read().split())
    return sum(values) / len(values)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM