【问题标题】:Trying to remove \n from my list but keeps coming up with an error试图从我的列表中删除 \n 但不断出现错误
【发布时间】:2021-09-23 03:55:18
【问题描述】:

所以我终于成功了,这样我就可以从我的文本文件中读取并将其添加到列表中。但现在我有一个小问题,每个值看起来像这样 6\n。我该如何解决这个问题我需要重组我的代码。 下面是代码。

错误:

Number guessing game with highscores.py", line 42, in <module>
    highscoreS = [highscores.replace("\n", "") for highscores in highscoreS]
NameError: name 'highscoreS' is not defined

虽然我已经明确定义了

from random import randint
a = True
n = randint(1,10)
guesses = 0

#If scores ever need to be reset just run function
def overwritefile():
    f = open("Numbergame.txt", "w")
    f.close()

#overwritefile()
#Guessing Game Code
while a == True:
    guess = int(input("What is your guess? \nEnter a number!"))
    if guess > n:
        print("Guess is too high! \nTry Again!")
        guesses += 1
    elif guess < n:
        print("Guess is too low! \nTry Again!")
        guesses += 1
    else:
        guesses += 1
        a = False

print("You guessed the number! \nIt was " + str(n) + "\nIt took you: " + str(guesses) + " guesses")

#Adding Score to the file
f = open("Numbergame.txt", "a")
f.write(str(guesses) + '\n')
f.close()


highscores = []
#Compare values and figure out if it is a new highscore
#Maybe I will use the TRY thing got taught recently might help iron out some errors
#f = open("Numbergame.txt").readlines()
with open('Numbergame.txt', 'rt') as f:
    for highscore in f:
        highscores.append(highscore)
        highscoreS = [highscores.replace('\n', '') for highscores in highscoreS]

【问题讨论】:

  • 产生错误的代码与您共享的代码不同。无论如何,如果您的代码实际上有highscoreS = [highscores.replace("\n", "") for highscores in highscoreS],这意味着highscoreShighscores 被视为单独的变量,因为Python 区分大小写。我假设您打算区分这两者,即使将它们命名为几乎相同的东西并不是一个好习惯。这意味着您对highscoreS 的定义依赖于它已经存在并具有价值。因此,此时,highscoreS 尚未定义。为什么你认为它是在那个时候定义的?
  • 失败的行不在您发布的代码中。这里似乎有一个小写/大写S 的事情。这是故意的吗?
  • 最好是highscores.append(highscore.strip())
  • @tdelaney 这是故意的,因为我正在尝试在我正在复制的一些代码上看到的东西,但它似乎对我不起作用。
  • 我在修复代码中进行了编辑以显示错误所在

标签: python list


【解决方案1】:

“虽然我已经明确定义了”

您需要在使用它之前定义它。截至目前,highscoreS 用于定义它的同一行。正确的方法是先将所有值读入一个列表,然后然后使用你定义的列表。

highscores = []
with open('Numbergame.txt', 'rt') as f:
    for line in f:
        highscores.append(line)

# Notice this is OUTSIDE the loop
highscoreS = [hs.replace('\n', '') for hs in highscores]

要覆盖原来的highscores,可以这样做

highscores = [hs.replace('\n', '') for hs in highscores]

但是,这不必要地令人费解。不要这样做,我建议您在阅读乐谱时只需strip() 空格

highscores = []
with open('Numbergame.txt', 'rt') as f:
    for line in f:
        highscores.append(line.strip()) # Or line.replace('\n', '')

您可能还希望将值转换为整数,在这种情况下,当您从文件中读取行时,在循环中也这样做是有意义的。

highscores = []
with open('Numbergame.txt', 'rt') as f:
    for line in f:
        highscores.append(int(line)) # No need to strip because `int()` automatically takes care of that

正如@tdelaney 所提到的,您可以将其进一步压缩为pythonic 列表理解:

with open('Numbergame.txt', 'rt') as f:
    highscores = [int(line) for line in f]

【讨论】:

  • 感谢您的帮助,这对我很有帮助,因为我还是编码新手,并没有完全理解我做错了什么。
  • @KGGamingFluff 很高兴为您提供帮助。考虑支持有用的答案并接受可以解决您的问题的答案。 What should I do when someone answers my question? 欢迎来到 Stack Overflow!
  • 好答案,它甚至可以浓缩为打开文件然后highscores = [int(line) for line in f] 无需预先定义列表或带有附加的for循环。
  • 这就是我最后所做的,我真的被这个问题困扰了很久。
  • @PranavHosangadi 目前由于我拥有的声望,我无法投票,因为我需要 15 个并且我有一个。我能做的就是感谢您的帮助。
猜你喜欢
  • 2023-02-14
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
  • 2019-12-05
  • 2019-05-12
  • 1970-01-01
相关资源
最近更新 更多