好的,我在做一个文本文件问题,并且90%的工作已经完成。尽管我在代码末尾打印了两个名称(都在不同的行上),但我正在尝试弄清楚如何在同一行上打印它们,特别是这样:(“ Best students:” name +“” + name)(可能有两个以上的名称,具体取决于文本文件中的文本)。我尝试使用end =“”将它们放在同一行上,并且它们之间有空格,这很好用。直到我不得不在它之前输入特定的文本,例如print(“ Best Students:”,name,end =“” ),但输出如下:
最佳学生:Michael Murphy最佳学生:John Kelly
预期产出:最佳学生:Michael Murphy,John Kelly 最佳成绩:89
任何对我有帮助的提示或想法都会受到赞赏。
谢谢
file = "students.txt"
with open(file,"r") as f:
q = []
for i in f:
i = i.split()
number = i[0]
q += (number,)
highest = max(q)
with open(file,"r") as f:
for i in f:
i = i.split()
number = i[0]
if highest == number:
name = " ".join(i[1:])
print("Best Students :",name,end=" ")
# print("Best Mark:",highest)
# Best Students : Michael Murphy, John Kelly
# Best mark: 89
Stduents.txt
64 Mary Ryan
89 Michael Murphy
22 Pepe
78 Jenny Smith
57 Patrick James McMahon
89 John Kelly
22 Pepe
74 John C. Reilly
答案 0 :(得分:0)
with open(file,"r") as f:
names = ""
for i in f:
i = i.split()
number = i[0]
if highest == number:
if names != "": names += ", "
names += " ".join(i[1:])
print("Best Students :",names)
像这样修改第二部分。我得到了这个输出
Best Students : Michael Murphy, John Kelly
答案 1 :(得分:0)
这是另一个答案:
file = "students.txt"
def get_highest_grade(input):
with open(input, "r") as f:
q = []
for i in f:
i = i.split()
number = i[0]
q += (number,)
highest = max(q)
return (highest)
def get_best_students(input, grade):
with open(input,'r') as f:
student_names = ''
for i in f:
i = i.split()
number = i[0]
if grade == number:
if student_names != '': student_names += ', '
student_names += ' '.join(i[1:])
print('Best Students: {} with a grade point of {}.'.format(student_names, grade))
# output
Best Students: Michael Murphy, John Kelly with a grade point of 89.
highest = get_highest_grade(file)
get_best_students(file,highest)
答案 2 :(得分:0)
您可能会有一个标志,那就是我们只会在第一次迭代中打印出“最佳学生”。
file = "students.txt"
with open(file,"r") as f:
q = []
for i in f:
i = i.split()
number = i[0]
q += (number,)
highest = max(q)
studentFound = False
with open(file,"r") as f:
for i in f:
i = i.split()
number = i[0]
if highest == number:
name = " ".join(i[1:])
if(not studentFound):
print("Best Students :",name,end=" ")
studentFound = True
else:
print(",",name, end=" ")
print("\nBest Mark:", highest)
结果
Best Students : Michael Murphy , John Kelly
Best Mark: 89