我想创建一个程序,该程序将通过创建 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')
等等... 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.