【问题标题】:How to join two different line specifically in text files?如何在文本文件中专门加入两个不同的行?
【发布时间】:2019-02-09 22:57:14
【问题描述】:

好的,我正在做一个文本文件问题,90% 的工作已经完成。虽然我在我的代码末尾打印了两个名字(都在不同的行),但我正在尝试弄清楚如何在同一行上打印它们,特别是这样 :("Best students: " name + " " + name) (可能有两个以上的名称,具体取决于文本文件中的文本)。我尝试使用 end="" 将它们放在同一行上,并且它们之间有空格,效果很好。直到我必须在它之前输入特定的文本,例如 print("Best Students :",name,end="" ) 但这给出了以下输出:

最好的学生:迈克尔·墨菲 最好的学生:约翰·凯利

预期产出:最佳学生:迈克尔·墨菲、约翰·凯利 最好成绩: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

【问题讨论】:

  • 请发布您的代码
  • 你尝试了什么?
  • 抱歉代码已发布

标签: python python-3.x


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    你可以有一个类似标志的东西,我们只会在第一次迭代中打印“最佳学生”。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      相关资源
      最近更新 更多