【问题标题】:How do I float an element of a list that is read from a file in Python 3.5?如何浮动从 Python 3.5 中的文件读取的列表元素?
【发布时间】:2017-04-21 20:12:19
【问题描述】:

我正在尝试从我打开并作为列表读取的文件中查找平均 GPA。该文件包含学生姓名、年龄和 GPA(例如 2.8),以逗号分隔,每个学生都有自己的行。我以逗号分隔,以便token[3] 成为 GPA。当我输入代码时,我收到Float object is not iterable 错误。如何浮动和/或定义字符串 (token[3]) 以便执行加法和除法等数学函数?

list=[]
f=open(file, 'r')
Sum = 0
for line in range(f):
    line=line.strip()
    token=line.split(',')
    list.append(token)
    print (sum(float(token[3])))

【问题讨论】:

  • 这里的错误是你在一个浮点数上调用sum(它接受一个可迭代的集合作为参数)。有点不清楚您实际上要打印什么。每行的 GPA 值?总和?
  • 问题是 sum()
  • 请发布一些简单的数据,即使你编码工作,为什么你只是求和一个浮点数?

标签: python list floating-point python-3.5


【解决方案1】:

这样的东西怎么样(希望可以扩展):

import statistics

gpa_grades = []
with open('grades.txt') as file:
    for line in file:
        gpa_grades.append(float(line.split(',')[3].strip()))

print("The average gpa is %f" % (sum(gpa_grades) / float(len(gpa_grades))))
print("The median gpa is %f" % statistics.median(gpa_grades))

示例等级.txt:

Bob,Smith,18,2.8
Simon,King,19,3.6
Jane,Doe,16,4.0

输出:

The average gpa is 3.466667
The median gpa is 3.600000

【讨论】:

  • 谢谢!这很有帮助。我没有想到将令牌浮动在附加行中。
猜你喜欢
  • 2017-01-19
  • 1970-01-01
  • 2014-11-28
  • 2017-08-29
  • 2012-11-12
  • 2013-12-18
  • 1970-01-01
  • 2020-03-07
  • 2016-10-27
相关资源
最近更新 更多