【问题标题】:Selecting a random value from a dictionary in python从python中的字典中选择一个随机值
【发布时间】:2015-01-09 22:31:59
【问题描述】:

这是我的功能:

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)

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

例如 {- - -, ['aah', 'aal', 'aas']}

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

【问题讨论】:

    标签: python-3.x dictionary random


    【解决方案1】:

    如果你有一个列表lst,那么你可以这样做:

    random_word = random.choice(lst)
    

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

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

    【讨论】:

    • 是的,但该列表当前存储为字典值。我不是必须先将它从字典中分离出来才能使用它吗?
    • 澄清了我的回答;而不是从字典中返回一个项目(它是一个长度为 2 的元组),而是在该项目的 [1] 条目上调用 random.choice 并返回结果。
    • 我实际上对此还有另一个问题。我编辑了我的主要帖子以包含我正在使用的主要代码。而不是在 evilSetup() 函数中制定随机,我怎样才能正确地使用它来将随机词存储在变量秘密词中?我在想诸如 secretWord = random.choice(words) 之类的东西,但这似乎只会通过整个字典。
    • @Droxbot 您最好将新问题作为一个单独的问题提出。
    猜你喜欢
    • 2015-05-25
    • 2020-03-17
    • 1970-01-01
    • 2016-04-14
    • 2020-04-04
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多