从python中的字典中选择一个随机值

时间:2014-11-12 22:16:19

标签: python-3.x dictionary random

这是我的功能:

def evilSetup():
    words = setUp()
    result = {}
    char = input('Please enter your one letter guess: ')
    for word in words:
        key = ' '.join(char if c == char else '-' for c in word)
        if key not in result:
            result[key] = []
        result[key].append(word)
    return max(result.items(), key=lambda keyValue: len(keyValue[1]))

from collections import defaultdict
import random
words= evilSetup()#list of words from which to choose
won, lost = 0,0 #accumulators for games won, and lost
while True:
    wrongs=0 # accumulator for wrong guesses
    secretWord = words
    print(secretWord) #for testing purposes
    guess= len(secretWord)*'_'
    print('Secret Word:' + ' '.join(guess))
    while wrongs < 8 and guess != secretWord:
        wrongs, guess = playRound(wrongs, guess)
    won, lost = endRound(wrongs,won,lost)
    if askIfMore()== 'N':
            break
printStats(won, lost)

该函数将获取单词列表,并根据猜测的字母的位置将它们排序到字典中。截至目前,它返回最大的键值对。我希望它最终返回的是来自最大字典条目的随机单词。现在的值是列表的形式。

例如{ - - - ,[&#39; aah&#39;,&#39; aal&#39;,&#39; aas&#39;]}

理想情况下,我会从此列表中获取一个随机单词返回。任何帮助表示赞赏。提前谢谢。

1 个答案:

答案 0 :(得分:1)

如果您有一个列表lst,那么您只需执行以下操作:

random_word = random.choice(lst)

获取列表的随机条目。所以在这里,你会想要这样的东西:

return random.choice(max(result.items(), key=lambda kv: len(kv[1]))[1])
#      ^^^^^^^^^^^^^^                                              ^^^^