我一直坚持这个任务,真的需要一些帮助。
我在文本文件中有一个数据:
John 46.5 Sam 62 Steve 45.5 Nigel 67.1 Karen 55
Henry 55 Alex 42 Graham 82 Hannah 56 Nicola 66
Ruth 81 Carl 90 Ben 66.8
并且需要编写一个程序,可以从文本文件中读取数据并在新行中输出每个名称和数字对,如下所示:
>>>
John : 46.5
Sam : 62
Steve : 45.5
Nigel : 67.1
Karen : 55
Henry : 55
Alex : 42
Graham : 82
Hannah : 56
Nicola : 66
Ruth : 81
Carl : 90
Ben : 66.8
AVERAGE: 62.684615384615384
>>>
我可以从文件中输出文本并分离它包含的元素,但是我无法设置条件中指定的正确输出。
f = open("grades.txt", "r")
d = f.read()
f.close()
print(d)
print()
d = d.splitlines()
print(d)
for line in d:
print(line)
line = line.split()
print (line)
print()
如果你能给我一些建议,帮我解决这个任务,我将不胜感激
提前致谢
您可以按行阅读文本,然后将其拆分为单词数组。试试这个:
values = []
with open('test.txt') as f:
lines = f.readlines()
for i in lines:
data = i.strip().split(' ')
counter = 0
for j in data:
if counter % 2 == 0:
string = ''
string += j + ' : '
else:
if round(float(j)) == int(float(j)):
values.append(int(float(j)))
string += j
else:
values.append(float(j))
string += j
print(string)
counter += 1
print('AVERAGE:',sum(values)/len(values))
with
语句和open
的组合打开文件并读取其内容。请注意,我们不需要它的"r"
参数,因为如果没有传递参数,它默认为"r"
。str.split
拆分文件的读取内容,当没有提供参数时默认拆分所有空格。i
始终是偶数。这意味着split_text[i]
总是一个名字,而split_text[i+1]
总是一个数字。print
和 fstring 输出名称和值。float
而不是 int
,因为如果我们使用后者,它会引发 ValueError
.len
的一半。 # Open the file and read the contents
with open("grades.txt") as file:
# split the contents on whitespace
split_text = file.read().split()
# Initialise the cumulative sum to zero
cumulative_sum = 0
# Iterate through the list with step size 2
for i in range(0, len(split_text), 2):
# Use slicing and multiple assignment to get the name and the value
name, value = split_text[i:i+2]
# Output the name and the value
print(f'{name} : {value}')
# Increase the cumulative sum
cumulative_sum += float(value)
# Output the final average
n = len(split_text)/2
print('AVERAGE:', cumulative_sum/n)
输出:
John : 46.5
Sam : 62
Steve : 45.5
Nigel : 67.1
Karen : 55
Henry : 55
Alex : 42
Graham : 82
Hannah : 56
Nicola : 66
Ruth : 81
Carl : 90
Ben : 66.8
AVERAGE: 62.684615384615384