Skip to main content
 首页 » 编程设计

python之随机短语创建器

2025年05月04日13JustinYoung

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

等等...使用 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. 

请您参考如下方法:

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

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

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

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

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