【问题标题】:Writing a program that prints out the name of students with more than six quiz score编写一个程序,打印出超过六个测验分数的学生的姓名
【发布时间】:2021-04-26 07:55:25
【问题描述】:

我是 Python 新手。请帮帮我。从"score.txt" 文件中,我必须打印出测验分数超过 6 的学生的姓名。如下

joe 10 15 20 30 40,
bill 23 16 19 22,
sue 8 22 17 14 32 17 24 21 2 9 11 17,
grace 12 28 21 45 26 10,
john 14 32 25 16 89

我最初的方法是这样从字符串中分离数据

f=open("score.txt", "r")
f.readlines()[1:]

这给了我一份清单。如何查看len(elements)>=6,然后打印名称?

【问题讨论】:

  • 您可以使用.split() 将每行的各个分数分开
  • 但输出来自 f.readlines()。如何在 f.readlines() 中使用 .split()?因为它给了我错误

标签: python python-3.x list


【解决方案1】:

由于它们是文件中的数据行,并且每一行都由空格分隔,因此您可以在此处使用字符串操作

f=open("score.txt", "r")
entries = f.readlines()

for entry in entries:
   # split entry by space, first is name, the rest are scores
   chunk = entry.split(' ')
   name = chunk[0]
   scores = chunk[1:]

   if len(scores) > 6:
      print(f'{name} had more than 6 quiz scores {len(scores)}')

【讨论】:

  • f.readlines()[1:]有什么用?你只是扔掉了文本文件的第一行......我知道这是提问者在他们的帖子中写的,但请考虑到提问者显然对他们在做什么不太了解......我建议写只是entries = f.readlines()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
  • 2022-10-24
  • 2016-12-09
  • 2019-07-12
相关资源
最近更新 更多