[英]Reading floats from a file Python
我的输入文件由一堆姓名和成绩组成,例如:
里奥·迪卡普里奥______4.5 6.5 7.5
肖恩·康纳利______ 3.5 8.5 5.5
[...]
我已经尝试了所有我能想到的方法,但总是遇到同样的问题,不能将 str 转换为 float 以获得成绩。 目标是计算每个人的平均成绩。
def average_grade(filename):
infile = open(filename, 'r')
floats = []
names = []
for line in infile:
words = line.split('_')
names.append(words[0])
floats.append(float(words[1]))
infile.close()
print(names)
'''Start'''
average_grade('grades1.txt')
你在这里很不正常。
您的行包含多个下划线_
字符。 拆分结果如下:
>>> line = 'Leo DiCaprio______4.5 6.5 7.5\n' #\n added to simulate a line read from a file.
>>> line.split('_')
['Leo DiCaprio', '', '', '', '', '', '4.5 6.5 7.5\n']
要访问“浮点数”,您需要获取拆分结果的最后一项。
>>> floats = line.split('_')[-1].strip() #strip out the '\n'
>>> floats
'4.5 6.5 7.5'
但是请注意,这里有多个数字,用空格分隔。 您不能一次全部转换为浮动,您需要再次拆分它们。
以下行将拆分组成项中的floats
,然后将它们转换为实际的浮点类型。
>>> numbers = [float(x) for x in floats.split()]
>>> numbers
[4.5, 6.5, 7.5]
现在,我想您可能想用名称和数字制作一个表格。 最简单的方法是使用字典。
另外,我建议不要使用floats
作为变量名,你很容易将它与float
类型混淆。 找到一个更好的名字。 我不确定这些数字是什么,所以我将在下面的代码中将其称为numbers
,但您应该选择一个正确的名称,例如scores
或grades
或它们实际上是什么。
table = {}
with open('grades1.txt', 'r') as f: #use the with statement to open files!
for line in f:
words = line.strip().split('_')
name = words[0]
numbers = [float(x) for x in words[-1].split()]
table[name] = numbers
for k,v in table.items():
print(k, v)
您可以在输入文件上使用正则表达式,以获取每个人的成绩以及他们的姓名。 所以在文件的每一行上运行一个 for 循环,得到每个人的名字和他们的成绩。 获得成绩后,您可以按空格(或分隔它们的任何内容)拆分成绩字符串。 这将创建一个列表,您可以使用该列表并将每个成绩字符串转换为浮点数,然后您就知道如何从那里计算平均值:)
让我知道这是否适合您!
我可以为您提供解决方案,但我想帮助您了解您的工作。
首先,我更改了您的代码,使其无需单独的文件即可工作。
这不是你应该做的,但这有助于我将代码分开。
def average_grade(data):
floats = []
names = []
for line in data:
words = line.split('_')
names.append(words[0])
floats.append(float(words[1]))
print(names)
average_grade('Leo DiCaprio______4.5 6.5 7.5', 'Sean Connery______ 3.5 8.5 5.5')
当我执行此代码时,我得到ValueError: could not convert string to float:
以及。
但为什么? 那么,让我们更改代码:
def average_grade(data):
floats = []
names = []
for line in data:
words = line.split('_')
print(words)
names.append(words[0])
floats.append(float(words[1]))
print(names)
average_grade('Leo DiCaprio______4.5 6.5 7.5', 'Sean Connery______ 3.5 8.5 5.5')
这个print(words)
给了我们['Leo DiCaprio', '', '', '', '', '', '4.5 6.5 7.5']
我们看到我们分割线的技术还不是很好。
让我们更加努力:
def average_grade(*data):
floats = []
names = []
for line in data:
words = line.split('_', 1)
name = words[0]
cursor = len(name)
while line[cursor] == '_':
cursor += 1
grades = line[cursor:]
print((name, grades))
grades = grades.split()
print((name, grades))
grades = [float(i) for i in grades]
avg = sum(grades) / len(grades)
print((name, grades, avg))
names.append(name)
# Now, what to do with these grades? Do we add them all to the list?
floats.append(avg)
print(names)
print(floats)
average_grade('Leo DiCaprio______4.5 6.5 7.5', 'Sean Connery______ 3.5 8.5 5.5')
现在我们看看grades
列表是如何演变的:
('Leo DiCaprio', '4.5 6.5 7.5') # this is our "original", after eliminating the `_`s.
('Leo DiCaprio', ['4.5', '6.5', '7.5']) # This is a list of the strings representung the grades
('Leo DiCaprio', [4.5, 6.5, 7.5], 6.166666666666667) # This is a list of the numbers, along with their average
('Sean Connery', ' 3.5 8.5 5.5') # from here on, the same for Sean
('Sean Connery', ['3.5', '8.5', '5.5'])
('Sean Connery', [3.5, 8.5, 5.5], 5.833333333333333)
['Leo DiCaprio', 'Sean Connery']
[6.166666666666667, 5.833333333333333]
我希望这会有所帮助。
请注意,我在____
部分的拆分方式有点“手动”; 使用正则表达式等其他技术肯定会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.