获取文本文件中的整数平均值(使用Python)

时间:2018-01-21 15:44:27

标签: python python-2.7 int text-files average

这是我的代码:

results = [[usernme, score]]

with open("hisEasyR.txt", "a") as hisEasyRFile:
        writer = csv.writer(hisEasyRFile, delimiter='|')
        writer.writerows(results)

这就是文本文件的样子:

mary|4
john|5
ben|3

我想取所有整数并计算平均值。 例如,对于此文件,我希望它输出:

The average is 4. 

我将如何做到这一点?

3 个答案:

答案 0 :(得分:1)

您可以使用list comprehension

with open("hisEasyR.txt") as hisEasyRFile:
    numbers = [int(line.rstrip('\n').split('|')[-1])
               for line in hisEasyRFile if not line.isspace()]

print "The average is %d." % (sum(numbers) / len(numbers))
# The average is 4.

答案 1 :(得分:0)

漫长的道路: 逐行读取,在|上使用字符串拆分。 然后取第二个字符串(即数字),并将其转换为int。

请参阅:https://www.tutorialspoint.com/python/string_split.htm

伪:

sum = 0

For line in file:
     mySplit = str.split(line, '|')
     sum += int(mySplit[1])

avg = sum/numLines

答案 2 :(得分:0)

分为两行:(假设您已将整个文件读到content

new_list = [int(i.split("|")[1]) for i in content.split("\n") if "|" in i]
print "The average is " + str(sum(new_list) / float(len(new_list)))