找出Python中的平均值
我正在读取 .txt 文件,每个人都有四个分数,我需要找出如何从每一行中获取分数并找到每个人的平均值。
s={}
results= open("surf.txt")
for line in results:
(s['Name'], s['scoreOne'], s['scoreTwo'], s['scoreThree'], s['scoreFour']) =line.split(";")
这似乎是解决这个问题所需的所有代码。
surf.txt 包含:
Johnny;8.65;7.32;7.81;9.12
Juan;9.12;8.45;8.80;5.60
Joseph;8.45;9.00;9.12;9.13
Stacey;7.81;8.33;9.00;8.10
(...)
I'm reading from a .txt file and have four scores for each person, i need to find out how to take the scores from each line and find the average for each person.
s={}
results= open("surf.txt")
for line in results:
(s['Name'], s['scoreOne'], s['scoreTwo'], s['scoreThree'], s['scoreFour']) =line.split(";")
That seems like all the code that's needed to figure this out.
surf.txt contains:
Johnny;8.65;7.32;7.81;9.12
Juan;9.12;8.45;8.80;5.60
Joseph;8.45;9.00;9.12;9.13
Stacey;7.81;8.33;9.00;8.10
(...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
解决方案:
输入:
输出:
Solution:
Input:
Output:
如果您的文件具有以下格式:
那么您可以简单地:
请注意,如果该人有多个姓名,则此示例将不起作用:它假设该姓名只有一列,其余列可以转换为浮点数。
If your file has the following format:
Then you can simply:
Notice that this example would NOT work if the person had more than one name: it assumes that there is only ONE column for the name, and the remaining columns can be converted to floats.
您可以使用
[1:]
对结果列表进行切片,这也更通用,因为您不会依赖于分数的数量,只需拒绝第一个元素:)
You can slice the result list with
[1:]
that's also more general, because you won't depend on number of scores, just reject the first element :)
文件cici.csv
代码
结果
file cici.csv
code
result