【问题标题】:List: How to create a new list from a Max Count列表:如何从最大计数创建新列表
【发布时间】:2013-04-12 18:44:34
【问题描述】:
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()

我正在用 Python 编写一个名为 Evil Hangman 的程序。基本上,给定一个 170,000 个单词的列表,我必须尽可能让用户获胜。所以对于每个用户的猜测,比如“A”,我根据“A”在单词中出现的位置将单词放入family,然后选择最大的family,打印“A”出现在哪里那个家庭。无论用户决定多久,这都会持续下去。我的问题是我想不出一种方法来为我的 while 循环创建一个新的单词列表。这个新列表将只包含最大的家庭中的单词。我想,

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

会起作用,但我不知道为什么它不起作用。非常感谢任何和所有帮助。另外,我是 Python 新手,并已尽力解释我的问题,但如果您有任何问题,请随时提问。

【问题讨论】:

  • 关于python 3的问题请不要使用python-2.7标签。

标签: python list python-3.x


【解决方案1】:

从查看代码看来,您可以从此更改 while 循环的结尾:

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

到这里:

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

由于Answer 将是来自result 的键,它为您提供最大的家庭,result[Answer] 将是最大的家庭,您只需将possible_words 重新分配给该值。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-17
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
  • 2020-01-25
  • 1970-01-01
  • 2021-05-01
相关资源
最近更新 更多