【问题标题】:Program will not let me store only the last three scores of the user程序不会让我只存储用户的最后三个分数
【发布时间】:2015-04-29 11:00:51
【问题描述】:
if class_number == 0:
    #This will create and open a new text file under the name
    #of the class_tag variable.
    file = open("Class 0" + ".txt", "a")
    #This will write down the user's name and their score
    file.write(str(name) + " scored " + str(score))
    #This will create a new line for each user
    file.write("\n")
    #This will close the file.
    file.close()

import collections

def new3ElementDeque():
   return collections.deque([], 3)

nameTop3 = collections.defaultdict(new3ElementDeque)

with open("Class 0.txt") as f:
    for line in f:
        user, score = line.split(':')
        nameTop3[name].append(score)

我试图让程序只保存用户的最后三个分数,而不是将所有分数保存到文本文件中。

现在看起来像这样:

student scored 3
student scored 8
student scored 0
student scored 4
student scored 10
student scored 3
student scored 0
student scored 4

我希望它是这样的:

student scored 3
student scored 0
student scored 4

但是,IDLE shell 声明:

    name, score = line.split(':')
ValueError: need more than 1 value to unpack

如何让程序存储用户的最后三个分数并将其保存到文本文件中?

输入的名字是:

name = input("What is your name? ")

【问题讨论】:

  • 看起来line中没有':',所以当它试图用':'分割它时,结果只有一个元素,你不能分配user和@987654329 @ 因为只有一个元素。
  • user, score = line.split(':') 之前执行print line 并检查是否没有':'
  • Julien Spronck,我将如何使用“打印线”?像这样:'print line user, score = line.split('scored')?
  • 可以显示输入文件吗?
  • 我建议你通读 python 教程 (docs.python.org/2/tutorial)

标签: python file text python-idle


【解决方案1】:

line 中没有':',所以当它试图用':'分割它时,结果只有一个元素,你不能分配用户和分数,因为只有一个元素。

如果您文件中的所有行都类似于“blah scores x”,您可以将行 user, score = line.split(':') 替换为 user, score = line.split(' scored ')

with open("Class 0.txt") as f:
    for line in f:
        user, score = line.split(' scored ')
        nameTop3[user].append(score)

【讨论】:

  • 我更新了我的代码,一开始它可以工作,但是当我再次这样做时,它没有工作。
  • 出现了:name, score = line.split(' score ') ValueError: need more than 1 value to unpack
  • 并非文件中的所有行都像“blah score x”。在for line in f:name, score = line.split(' scored ') 行之间输入print line,然后告诉我们在错误消息之前屏幕上打印的内容。
  • 它在整个程序启动之前说“无效语法”,因为“行”。
  • 我不知道你所说的“因为`line”是什么意思。看看我刚刚在我的答案中发布的代码......我认为那里没有语法错误......是你尝试的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 2021-04-20
  • 1970-01-01
  • 2014-09-17
  • 2014-12-31
  • 2017-01-25
  • 2016-04-14
相关资源
最近更新 更多