如何在Python中随机选择

时间:2018-11-06 12:34:19

标签: python-3.x

我必须用python编写代码,该代码从7个列表中选择一个单词(总共7个单词),然后运行请求的行数以形成“诗歌”。 “诗歌”的每一行都应是7个列表的不同组合。关于如何使程序运行不同组合的任何想法?我的行数和我问过的次数相同:

people=['Amir', 'Itai', 'Sheli','Gil','Jasmin','Tal','Nadav']
verbs = ['talks', 'smiles', 'sings', 'listens', 'eats', 'waves', 'plays', 'swims']
Adverbs =['slowly',  'quickly', 'solemnly', 'nicely', 'beautifully']
Prepositions=['to a', 'with a' ,'towards a', 'at a' ,'out of a']
Adjectives =['white', 'blue', 'green', 'small', 'large', 'yellow', 'pretty', 'sad']
Animated=['fish', 'parrot', 'flower', 'tree', 'snake']
Inanimated=['chair', 'lamp', 'car', 'ship', 'boat']

x=eval(input("How many lines are in the poem?"))
y=(random.choice(people), random.choice (verbs) ,random.choice(Adverbs) ,random.choice(Prepositions) ,random.choice(Adjectives) ,random.choice(Animated+Inanimated))
for i in range (x):
   if (x< 10):
        print (y)

2 个答案:

答案 0 :(得分:1)

您有正确的主意,但每次只需要重新评估随机选择:

people=['Amir', 'Itai', 'Sheli','Gil','Jasmin','Tal','Nadav']
verbs = ['talks', 'smiles', 'sings', 'listens', 'eats', 'waves', 'plays', 'swims']
Adverbs =['slowly',  'quickly', 'solemnly', 'nicely', 'beautifully']
Prepositions=['to a', 'with a' ,'towards a', 'at a' ,'out of a']
Adjectives =['white', 'blue', 'green', 'small', 'large', 'yellow', 'pretty', 'sad']
Animated=['fish', 'parrot', 'flower', 'tree', 'snake']
Inanimated=['chair', 'lamp', 'car', 'ship', 'boat']

x=eval(input("How many lines are in the poem?"))
for i in range (x):
    y=(random.choice(people), random.choice (verbs) ,random.choice(Adverbs) ,random.choice(Prepositions) ,random.choice(Adjectives) ,random.choice(Animated+Inanimated))
    if (i < 10):
        print (y)

答案 1 :(得分:0)

我认为这可以为您提供帮助

import random

people=['Amir', 'Itai', 'Sheli','Gil','Jasmin','Tal','Nadav']
verbs = ['talks', 'smiles', 'sings', 'listens', 'eats', 'waves', 'plays', 'swims']
Adverbs =['slowly',  'quickly', 'solemnly', 'nicely', 'beautifully']
Prepositions=['to a', 'with a' ,'towards a', 'at a' ,'out of a']
Adjectives =['white', 'blue', 'green', 'small', 'large', 'yellow', 'pretty', 'sad']
Animated=['fish', 'parrot', 'flower', 'tree', 'snake']
Inanimated=['chair', 'lamp', 'car', 'ship', 'boat']

while True:
    x=eval(input("How many lines are in the poem?"))
    if x == 0:
        break
    for i in range (x):
        if (x< 10):
            y = (random.choice(people), random.choice(verbs), random.choice(Adverbs), random.choice(Prepositions),random.choice(Adjectives), random.choice(Animated + Inanimated))
            print (y)