Python 从文件中计算平均值和总计
Python初学者。 如何显示文件中的数据并计算每个人的总/平均值? 在每次迭代中,如何将值添加到for之外的变量中,并且在迭代结束后将其除以记录数 文件中的数据会有所不同,因为用户可以添加和删除数据,但数据的结构如下:Python 从文件中计算平均值和总计,python,Python,Python初学者。 如何显示文件中的数据并计算每个人的总/平均值? 在每次迭代中,如何将值添加到for之外的变量中,并且在迭代结束后将其除以记录数 文件中的数据会有所不同,因为用户可以添加和删除数据,但数据的结构如下: PersonA;342;454;559; PersonB;444;100;545; PersonC;332;567;491; PersonD;142;612;666; 我想这样呈现: PersonA 342 454 559 TOTAL AVERA
PersonA;342;454;559;
PersonB;444;100;545;
PersonC;332;567;491;
PersonD;142;612;666;
我想这样呈现:
PersonA 342 454 559 TOTAL AVERAGE
PersonB 444 100 545 TOTAL AVERAGE
PersonC 332 567 491 TOTAL AVERAGE
PersonD 142 612 666 TOTAL AVERAGE
在这之后我能写些什么来做对呢
def show_result():
text_file = open('result.txt', 'r')
for line in text_file:
if ';' in line:
line2 = line.split(";")
print line2
?
解决方案:
def show_result():
text_file = open('minigolf.txt', 'r')
print "Name,Round1,Round2,Round3"
for line in text_file:
if ';' in line:
line2 = line.split(";")[:-1]
print line2
line_total = sum(map(int, line2[1:]))
line_average = line_total / len(line2[1:])
print "Total: ", line_total
print "Average: ", line_average
要计算
总数
,您只需执行以下操作(假设您不希望包含第一个索引,其中包含“PersonA”等):
由此得出的平均值也很简单:
line_average = line_total / len(line2[1:])
说明:
函数接收一个iterable(出于我们的目的,将iterable看作一个列表),并使用适当的sum函数添加其所有内容sum
[1://code>称为列表拼接。使用这种语法,您告诉Python您想要创建一个新列表,原始列表的内容从
位置开始。这里有几个例子:1
>>> a = [1, 2, 3] >>> b = [1:] >>> b [2, 3]
具体语法如下:
[start\u index:end\u index]
可以将start\u index
或end\u index
保留为空,Python将分别用列表的开头或结尾填充它们 要计算总数
,您可以简单地执行以下操作(假设您不想包括第一个索引,其中包含“PersonA”等):
s = """PersonA;342;454;559;
PersonB;444;100;545;
PersonC;332;567;491;
PersonD;142;612;666;"""
for line in s.split("\n"):
p, a, b, c, _ = line.strip().split(";")
print("{}\t{}\t{}\t{}\t{}\t{}".format(p, a, b, c,
sum([int(a), int(b), int(c)]),
sum([int(a), int(b), int(c)]) / 3))
由此得出的平均值也很简单:
line_average = line_total / len(line2[1:])
说明:
函数接收一个iterable(出于我们的目的,将iterable看作一个列表),并使用适当的sum函数添加其所有内容sum
[1://code>称为列表拼接。使用这种语法,您告诉Python您想要创建一个新列表,原始列表的内容从
位置开始。这里有几个例子:1
>>> a = [1, 2, 3] >>> b = [1:] >>> b [2, 3]
[start\u index:end\u index]
可以将start\u index
或end\u index
保留为空,Python将分别用列表的开头或结尾填充它们
s = """PersonA;342;454;559;
PersonB;444;100;545;
PersonC;332;567;491;
PersonD;142;612;666;"""
for line in s.split("\n"):
p, a, b, c, _ = line.strip().split(";")
print("{}\t{}\t{}\t{}\t{}\t{}".format(p, a, b, c,
sum([int(a), int(b), int(c)]),
sum([int(a), int(b), int(c)]) / 3))
输出:
PersonA 342 454 559 1355 451.6666666666667
PersonB 444 100 545 1089 363.0
PersonC 332 567 491 1390 463.3333333333333
PersonD 142 612 666 1420 473.3333333333333
0 1 2 3 AVERAGE TOTAL
0 PersonA 342 454 559 451.666667 1355
1 PersonB 444 100 545 363.000000 1089
2 PersonC 332 567 491 463.333333 1390
3 PersonD 142 612 666 473.333333 1420
编辑:
如果要读取文件,可以执行以下操作:
with open("input.txt") as f:
for line in f:
# same as above: split the line, etc.
输出:
PersonA 342 454 559 1355 451.6666666666667
PersonB 444 100 545 1089 363.0
PersonC 332 567 491 1390 463.3333333333333
PersonD 142 612 666 1420 473.3333333333333
0 1 2 3 AVERAGE TOTAL
0 PersonA 342 454 559 451.666667 1355
1 PersonB 444 100 545 363.000000 1089
2 PersonC 332 567 491 463.333333 1390
3 PersonD 142 612 666 473.333333 1420
编辑:
如果要读取文件,可以执行以下操作:
with open("input.txt") as f:
for line in f:
# same as above: split the line, etc.
我会这样做的。这就是说,有很多方法可以在Pyton实现这一点
import pandas as pd
df = pd.read_csv('result.txt', sep=';',header=None)
del df[4]
df['AVERAGE'] = df[[1,2,3]].mean(axis = 1)
df['TOTAL'] = df[[1,2,3]].sum(axis = 1)
我使用库进行这种类型的操作
输出:
PersonA 342 454 559 1355 451.6666666666667
PersonB 444 100 545 1089 363.0
PersonC 332 567 491 1390 463.3333333333333
PersonD 142 612 666 1420 473.3333333333333
0 1 2 3 AVERAGE TOTAL
0 PersonA 342 454 559 451.666667 1355
1 PersonB 444 100 545 363.000000 1089
2 PersonC 332 567 491 463.333333 1390
3 PersonD 142 612 666 473.333333 1420
我会这样做的。这就是说,有很多方法可以在Pyton实现这一点
import pandas as pd
df = pd.read_csv('result.txt', sep=';',header=None)
del df[4]
df['AVERAGE'] = df[[1,2,3]].mean(axis = 1)
df['TOTAL'] = df[[1,2,3]].sum(axis = 1)
我使用库进行这种类型的操作
输出:
PersonA 342 454 559 1355 451.6666666666667
PersonB 444 100 545 1089 363.0
PersonC 332 567 491 1390 463.3333333333333
PersonD 142 612 666 1420 473.3333333333333
0 1 2 3 AVERAGE TOTAL
0 PersonA 342 454 559 451.666667 1355
1 PersonB 444 100 545 363.000000 1089
2 PersonC 332 567 491 463.333333 1390
3 PersonD 142 612 666 473.333333 1420
这将适用于任何人均值和任何人数:
from collections import defaultdict
def myprint(lines):
sum_dict = defaultdict(lambda: ([], 0, 0))
for line in lines:
data = line.strip().split(";")
person = data[0].strip()
values = [int(i) for i in data[1:] if i]
sum_dict[person] = (values + sum_dict[person][0], sum(values)+sum_dict[person][1], len(values)+sum_dict[person][2])
for person in sorted(sum_dict):
values, total, nb = sum_dict[person]
print "{}\t{}\t{}\t{}".format(person, '\t'.join([str(i) for i in values]), total, total/nb)
if __name__ == '__main__':
import os
if os.path.exists('result.txt'):
with open('result.txt') as input:
lines = input.readlines()
else:
s = """PersonA;342;454;559;
PersonB;444;100;545;
PersonC;332;567;491;
PersonD;142;612;666;"""
lines = s.split('\n')
myprint(lines)
这将适用于任何人均值和任何人数:
from collections import defaultdict
def myprint(lines):
sum_dict = defaultdict(lambda: ([], 0, 0))
for line in lines:
data = line.strip().split(";")
person = data[0].strip()
values = [int(i) for i in data[1:] if i]
sum_dict[person] = (values + sum_dict[person][0], sum(values)+sum_dict[person][1], len(values)+sum_dict[person][2])
for person in sorted(sum_dict):
values, total, nb = sum_dict[person]
print "{}\t{}\t{}\t{}".format(person, '\t'.join([str(i) for i in values]), total, total/nb)
if __name__ == '__main__':
import os
if os.path.exists('result.txt'):
with open('result.txt') as input:
lines = input.readlines()
else:
s = """PersonA;342;454;559;
PersonB;444;100;545;
PersonC;332;567;491;
PersonD;142;612;666;"""
lines = s.split('\n')
myprint(lines)
如何计算每个人的总数和平均数?你是指第2、3和4列的总数/平均数吗?如何计算每个人的总数和平均数?你是指第2、3和4列的总和/平均值吗?请注意输入是字符串,而不是int。但是这与我编写的代码结合起来会是什么样子,因为现在我得到了一个错误:文件“C:\Users\HKI\Desktop\test3.py”,第32行,在show\u result line\u total=sum(map(int,line2[1:])ValueError:int的无效文本()对于base 10:“”请注意,输入是字符串,而不是int。但是这与我编写的代码一起会是什么样子,因为现在我得到一个错误:文件“C:\Users\HKI\Desktop\test3.py”,第32行,在show\u result line\u total=sum(map(int,line2[1:])ValueError:int()的文本无效,基数为10:“”但这是否从文件中获取数据?数据存储在result.txt中,类似于PersonA;342;454;559;我的解释可能有点不清楚。因为用户可以在result.txt中删除和添加数据,所以PersonA可能不存在,但是PersonQ可能在某一次存在,但在下一次不存在。当我不知道文件中不时有哪些人时,我如何从文件中获取数据,将其放到不同的行中,并计算总/平均值?您可以使用更改的文件重新运行计算。现在,它将接收文件中提到的每个人。请不要将代码,尤其是Python代码,放入注释中。它不可读。好的,对不起。如果你想看的话,我已经更新了描述:)但是这是从文件中获取数据的吗?数据存储在result.txt中,类似于PersonA;342;454;559;我的解释可能有点不清楚。因为用户可以在result.txt中删除和添加数据,所以PersonA可能不存在,但是PersonQ可能在某一次存在,但在下一次不存在。当我不知道文件中不时有哪些人时,我如何从文件中获取数据,将其放到不同的行中,并计算总/平均值?您可以使用更改的文件重新运行计算。现在,它将接收文件中提到的每个人。请不要将代码,尤其是Python代码,放入注释中。它不可读。好的,对不起。如果你想看的话,我已经更新了描述:)