随机短语创作者

Joh*_*ell 1 python python-3.3

我想创建一个程序,通过创建10个从1到20的随机整数来生成随机短语,并且根据每个变量整数,将生成某个单词或短语.有没有比以下更简单的方法:

#This is a random phrase generator
import random
Rand1 = random.randint (1, 20)
Rand2 = random.randint (1, 20)
Rand3 = random.randint (1, 20)
Rand4 = random.randint (1, 20)
Rand5 = random.randint (1, 20)
Rand6 = random.randint (1, 20)
Rand7 = random.randint (1, 20)
Rand8 = random.randint (1, 20)
Rand9 = random.randint (1, 20)
Rand10 = random.randint (1, 20)
    if Rand1 ==1:
        print ('Squirrel')
Run Code Online (Sandbox Code Playgroud)

等等... PS使用Python 3

感谢您提供有用的建议.我是python的新手,让那些可以帮助我创建更好代码的人非常有帮助.如果有人关心,我用这个与你交谈的程序,让你有机会听到笑话和玩几个游戏.祝你今天愉快.

PPS我最终选择了:

import random
words = 'squirrel orca ceiling crayon boot grocery jump' .split()
def getRandomWord(wordList):
    # This function returns a random string from the passed list of strings.
    wordIndex = random.randint(0, len(wordList) - 1)
    return wordList[wordIndex]
potato = getRandomWord(words)
print (potato) # plus of course all the other words... this is just the base.
Run Code Online (Sandbox Code Playgroud)

Lev*_*sky 10

当然.使用Python列表和/或词典.如果您从一个组中选择:

words = ['Some', 'words', 'any', 'number', 'of', 'them']
choices = [random.choice(words) for _ in range(10)]
print(' '.join(choices))
Run Code Online (Sandbox Code Playgroud)

如果没有,您可以使用嵌套列表:

words = [['Sam', 'Joe'], ['likes', 'hates'], ['apples', 'drugs', 'jogging']]
choices = [random.choice(group) for group in words]
print(' '.join(choices))
Run Code Online (Sandbox Code Playgroud)

这可以扩展到每个组中的任意数量的组和单词.