python - 如何找到一个文件的平均值然后将其放入另一个文件
问题描述
我想找到 inFile 列表的平均值,然后我想将它移动到 classescores。
classgrades.txt
是:
Chapman 90 100 85 66 80 55
Cleese 80 90 85 88
Gilliam 78 82 80 80 75 77
Idle 91
Jones 68 90 22 100 0 80 85
Palin 80 90 80 90
classcores.txt
是空的
这就是我目前所拥有的......我该怎么办?
inFile = open('classgrades.txt','r')
outFile = open('classscores.txt','w')
for line in inFile:
with open(r'classgrades.txt') as data:
total_stuff = #Don't know what to do past here
biggest = min(total_stuff)
smallest = max(total_stuff)
print(biggest - smallest)
print(sum(total_stuff)/len(total_stuff))
解决方案
您将需要:
- 用空格分割每一行并切掉除第一个以外的所有项目
- 将数组中的每个字符串值转换为整数
- 将数组中的所有整数值
相加 - 将此行的总和添加到 total_sum
- 添加这些值的长度(数字的数量)到 total_numbers
然而,这只是问题的一部分......我将把剩下的留给你。此代码不会写入新文件,它只会取第一个文件中所有数字的平均值。如果这不是你所要求的,那么试着玩弄这些东西,你应该能够弄清楚。
inFile = open('classgrades.txt','r')
outFile = open('classscores.txt','w')
total_sum = 0
total_values = 0
with open(r'classgrades.txt') as inFile:
for line in inFile:
# split by whitespace and slice out everything after 1st item
num_strings = line.split(' ')[1:]
# convert each string value to an integer
values = [int(n) for n in num_strings]
# sum all the values on this line
line_sum = sum(values)
# add the sum of numbers in this line to the total_sum
total_sum += line_sum
# add the length of values in this line to total_values
total_numbers += len(values)
average = total_sum // total_numbers # // is integer division in python3
return average
推荐阅读
- java - 在 MacOS 上安装 R 并从源代码编译包 - 组件和步骤以使事情正常运行
- reactjs - 如何在 TypeScript 中创建一个让我处理事件的 React 组件?
- sql - 如何计算两个日期之间的月数和天数,而不在 SQL Server 中返回负值
- java - 为什么 JSON 没有被解组到我的 Java 类中?
- python - 如何使用 tkinter 和 turtle 获得鼠标位置?
- apache-poi - 由于 xmlbeans 在 weblogic 中卡住了线程
- javascript - 为什么 Phantomjs 不适用于此站点?
- sql - 为什么我的子查询使用字符串而不是字段引用?
- php - 是否可以从 PHP 文件发送标头,这完全没有任何作用
- rasa-core - Rasa 自定义操作事件丢失