Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在python中从字典中选择随机值_Python 3.x_Dictionary_Random - Fatal编程技术网

Python 3.x 在python中从字典中选择随机值

Python 3.x 在python中从字典中选择随机值,python-3.x,dictionary,random,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: r

以下是我的功能:

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)
def-setup():
words=setUp()
结果={}
char=input('请输入您的一个字母猜测:')
用文字表示:
key=''.join(如果c==char else'-'表示word中的c,则为char)
如果键不在结果中:
结果[键]=[]
结果[关键字]。追加(word)
返回最大值(result.items(),key=lambda keyValue:len(keyValue[1]))
从集合导入defaultdict
随机输入
Word=evilSetup()#要从中选择的单词列表
赢、输=0,0#赢、输游戏的累加器
尽管如此:
错误=0#错误猜测累加器
秘密词语
打印(秘密文字)#用于测试
猜=len(秘密单词)*''
print('secretword:'+'.join(猜测))
当错误<8且猜猜!=秘密:
错误,猜测=游戏回合(错误,猜测)
赢了,输了=结束(错了,赢了,输了)
如果askIfMore()=“N”:
打破
printStats(赢、输)
该函数将获取单词列表,并根据猜测字母的位置将其排序到字典中。现在,它返回最大的键、值对。我希望它最终返回的是最大字典条目中的一个随机单词。到目前为止,这些值以列表的形式存在

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


理想情况下,我会从列表中随机抽取一个单词返回。感谢您的帮助。提前感谢。

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

random_word = random.choice(lst)
获取列表中的随机条目。因此,在这里,您将需要以下内容:

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

是,但列表当前存储为字典值。为了使用它,我不需要先把它和字典分开吗?我澄清了我的答案;不是从字典中返回一个项(长度为2的元组),而是调用该项的
[1]
条目上的
random.choice
,并返回该项的结果。实际上,关于这一点,我还有另一个问题。我编辑了我的主要帖子,加入了我正在使用的主要代码。如何正确地使用它将随机字存储在变量secret word中,而不是在evilSetup()函数中设置随机字?我想的是像secretWord=random.choice(单词)这样的东西,但这似乎只是通过了整本字典。@Droxbot你最好把你的新问题作为一个单独的问题来问。