我想为文字游戏创建计算机 Ghost 。然而,我在思考一种处理访问庞大单词列表的好方法时遇到了问题。这是我当前的实现(不起作用):
import os, random, sys, math, string
def main():
#Contains a huge wordlist-- opened up for reading
dictionary = open("wordlist.txt", "r")
wordlist = []
win= 0
turn= 0
firstrun = 0
word = ""
#while nobody has won the game
while win==0:
if turn == 0:
#get first letter from input
foo = raw_input("Choose a letter: ")[0]
word+=foo
print "**Current word**: "+ word
#Computer's turn
turn = 1
if turn == 1:
#During the first run the program gets all definitively
#winning words (words that have odd-number lengths)
#from the "dictionary" file and puts them in a list
if firstrun== 0:
for line in dictionary:
#if the line in the dictionary starts with the current
#word and has an odd-number of letters
if str(line).startswith(word) and len(line)%2 == 0:
wordlist.append(line[0: len(line)-1])
print "first run complete... size = "+str(len(wordlist))
firstrun = 1
else: #This is run after the second computer move
for line in wordlist:
#THIS DOES NOT WORK-- THIS IS THE PROBLEM.
#I want it to remove from the list every single
#word that does not conform to the current limitations
#of the "word" variable.
if not line.startswith(word):
wordlist.remove(line)
print "removal complete... size = "+str(len(wordlist))
turn = 0
if __name__ == "__main__":
main()
我已经在代码中划定了问题区域。我不知道为什么它不起作用。应该发生什么:假设列表中填充了所有以“a”开头的单词。然后用户选择字母“b”。目标单词必须以“ab”开头。应该发生的情况是,列表中所有未直接跟在“b”后面的“a”单词都应该被删除。
如果有人能让我知道一种更有效的方法来做到这一点,然后制作一个巨大的初始列表,我也将不胜感激。
最佳答案
我建议不要从列表中删除单词。它会非常慢,因为删除列表中间的时间复杂度为 O(N)。
最好只是制作一个新列表。一种可能的方法是更换线路
for line in wordlist:
if not line.startswith(word):
wordlist.remove(line)
与
wordlist = [w for w in wordlist if w.startswith(word)]
关于Python-文字游戏 "Ghost"、文件 I/O 和列表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4764553/