清单:如何从最大计数创建新列表

时间:2013-04-12 18:44:35

标签: python list python-3.x

def validateGuess():
    print(letters)
    inputGuess= input("Choose one of the letters above:")
    return inputGuess

def wordLength():
    length=input("Welcome to Hangman. How many letters in the secret word?")
    length1=int(length)
    if length1 <0:
        length=input("Welcome to Hangman. How many letters in the secret word?")
    return length    

def guessAmount():
    guesses=input("How many guesses would you like?")
    guesses1=int(guesses)
    if guesses1 < 0:
        guesses=input("How many guesses would you like?")
    return guesses

welcome=wordLength()
remain=input("Do you want to print the count of how many words remain [Y/N]?")
guessNumber=int(guessAmount())
F=open('dictionary.txt')
F1=F.readlines()

welcome2=int(welcome)
a_list=[word.strip('\n') for word in F1]
possible_words = [x for x in a_list if len(x) == welcome2]

letters= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

while guessNumber >0:
    letter_guess=validateGuess()
    letters.remove(letter_guess)
    guessNumber -= 1
    result={}
    for word in possible_words:
        key=' '.join(letter_guess if c == letter_guess else '-' for c in word)
        if key not in result:
            result[key]=[]
        result[key].append(word)
    inverse= [(len(value), key) for key, value in result.items()]
    Answer=max(inverse)[1]
    possible_words=result.values()
    print()

我正在编写一个名为Evil Hangman的Python程序。基本上,给定一个170,000个单词的列表,我必须尽可能地让用户赢得胜利。因此,对于每个用户猜测,例如“A”,我根据单词中出现“A”的位置将单词放入系列,然后选择最大的系列并打印“A”出现在哪里那个家庭。这种情况持续很长时间用户决定。我的问题是我无法想办法为我的while循环创建一个新的单词列表。这个新列表只包含最大家庭中的字词。我想,

for word in max(result):
     possible_words+=word

会起作用,但我无法弄清楚它为什么没有。任何和所有的帮助非常感谢。此外,我是Python的新手,并尽我所能解释我的问题,但如果您有任何问题,请不要犹豫。

1 个答案:

答案 0 :(得分:1)

从查看代码看起来你可以改变你的while循环的结束:

Answer=max(inverse)[1]
possible_words=result.values()

对此:

Answer=max(inverse)[1]
possible_words=result[Answer]

由于Answer将成为result的关键字,为您提供最大的系列,result[Answer]将是最大的系列,您可以将possible_words重新分配给该值。