【问题标题】:Using the random function in Python在 Python 中使用随机函数
【发布时间】: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


    【解决方案1】:

    为了参考和将来使用,我确实想出了如何做到这一点。我只是使用了不正确的语法。这是正常工作的代码行:

    secretWord = random.choice((words[1]))
    

    它现在从第一个位置的字典键对应的单词中生成一个随机单词。

    【讨论】:

      猜你喜欢
      • 2010-12-17
      • 2018-08-06
      • 2015-04-26
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多