如何在用户输入后永久更改列表?

2024-10-01 17:31:09 发布

您现在位置:Python中文网/ 问答频道 /正文

hiddenWords = ['hello', 'hi', 'surfing']
print("Would you like to enter a new list of words or end the game? L/E?")
    decision  = input()
    if decision == 'L':
        print('Enter a new list of words')
        newString = input()
        newList = newString.split()
        hiddenWords.extend(newList)
        j = random.randint(0, len(hiddenWords) - 1)
        secretWord = hiddenWords[j]
        exit(0)

如何将用户的输入永久添加到hiddenWords列表中,以便下次打开应用程序时,用户输入的单词将扩展到hiddenWords列表中?在

谢谢。 此代码是代码主体的一部分。在


Tags: of代码用户hello列表newinputhi
3条回答

当你写作的时候

hiddenWords = ['hello', 'hi', 'surfing']

每次程序运行时,都会将变量hiddenWords定义为['hello', 'hi', 'surfing']。 因此,无论在这之后进行什么扩展,每次代码运行上面的行时,它都会重新定义为该值。在

实际上,您需要的是使用数据库(如SQLite)来存储值,以便您可以随时检索值。 此外,您可以将数据保存在一个文件中,并在每次读取此文件,这是一种更简单的方法。在

当程序退出时,所有变量都会丢失,因为变量只在内存中退出。为了保存你的修改accross程序执行(每次你运行你的脚本),你需要把数据保存到磁盘上,也就是说:把它写入一个文件。泡菜确实是最简单的解决办法。在

我喜欢json。这将是一个可能的解决方案:

import json

words = []
try:
  f = open("words.txt", "r")
  words = json.loads(f.read())
  f.close()
except:
  pass

print("list:")
for word in words:
  print(word)
print("enter a word to add it to the list or return to exit")
add = raw_input() # for python3 you need to use input()

if add:
  words.append(add)
  try:
    f = open("words.txt", "w")
    f.write(json.dumps(words, indent=2))
    f.close()
    print("added " + add)
  except:
    print("failed to write file")

如果你想一次添加多个单词,请使用这个。在

^{pr2}$

相关问题 更多 >

    热门问题