【发布时间】:2014-11-13 00:03:18
【问题描述】:
这是我正在使用的函数以及需要返回值的主要代码:
def evilSetup():
"""takes a list of words of random length and places them into a dictionary based on the position of the chosen letter.Randomly selects a word from the key with the most words."""
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 = random.choice((words)[1])
print(secretWord) #for testing purposes
我要做的是让主代码中的 secretWord 变量从 evilSetup() 的返回值中存储一个随机词。从之前的一篇文章中我了解到我可以直接在函数中返回一个随机词:
return random.choice(max(result.items(), key=lambda kv: len(kv[1]))[1])
我需要基本上执行相同的操作,但将其存储在 secretWord 变量中,以便在每个新游戏中实际随机选择单词,而不是保留 evilSetup() 函数选择的相同单词。
【问题讨论】:
标签: python-3.x dictionary random