2017-06-02 12 views
0
import random 

#lists to describe what trucks people like 
person= ['I', 'she', 'he'] 
emtotion=['loves', 'hates', 'likes'] 
Trucks= ['chevys', 'fords', 'rams']` 

#lists to describe an animals favorite foods 
animal= ['dogs', 'cats', 'birds'] 
emotion_2=['love', 'hates'] 
food= ['tuna', 'meat', 'seeds', 'garbage'] 

对于上面的列表,我如何将两个单独列表中的三个列表分为两个独立的主类型列表?例如:如何将具有多个值的列表合并到主列表供用户选择?

# a main call to describe peoples emotions towards trucks 
truck_preference =  
person= ['I', 'she', 'he'] 
emtotion=['loves', 'hates', 'likes'] 
Trucks= ['chevys', 'fords', 'rams'] 

#a main call for all lists describing an animals foods 
animal_foods= 
animal= ['dogs', 'cats', 'birds'] 
emotion_2=['love', 'hates'] 
food= ['tuna', 'meat', 'seeds', 'garbage'] 

所以例如,一旦我有我的两个主要类别,我可以要求输入用户选择“animal_foods”或“truck_preference”和随机显示的值,以形成文本的一个字符串,一个简单的3个字随机文本。然后要求用户再次选择一个列表,这次是“animal_foods”,并再次显示相同的随机性。

这是我现在所拥有的打印随机项目。

count = 0 
while count < 10: 
     print(random.choice(Person), end= " ") 
     print(random.choice(Emotion), end= " ") 
     print(random.choice(Trucks), end= " ") 
     print('\n') 
     count = count +1 

count = 0 
    while count < 10: 
      print(random.choice(animal), end= " ") 
      print(random.choice(Emotion_2), end= " ") 
      print(random.choice(Food), end= " ") 
      print('\n') 
      count = count +1 

但是,我最大的问题是如何让一个用户选择了“Truck_preference”打印的项目随机形成随机文本,然后让用户选择“animal_foods”列表值形成关于这个的随机文本。

所以标识希望什么来完成总结是:

import random 

truck_preference = [3 key lists and their values] 
animal_foods =[3 key lists and their values] 

input("which scenario would you like to run") 
#user inputs Truck_preference 
output: I love chevys 
     he likes fords 
     she hates rams 
     he loves rams 
     i like fords 
     ....etc 

input("which scenario would you like to run") 
#user inputs animal_foods 
output: Cats hate seeds 
      dogs love meat 
      dogs hate meat 
     birds hate tuna 
     cats love tuna 
     birds love seeds 
     dogs love garbage 
     ...etc 

回答

1

这里是一个灵活的机制,使得它更直接的扩展,如果你既想更多的单词添加到每个垃圾桶或添加/重新排序更多的单词到一个特定的句子,甚至新单词/句子类共。

import random 

d_1 = { 
     0: ['I', 'He', 'She'], 
     1: ['loves', 'hates', 'likes'], 
     2: ['Chevys', 'Fords', 'Rams'] 
} 

d_2 = { 
     0: ['Cats', 'Dogs', 'Birds'], 
     1: ['love', 'hate'], 
     2: ['tuna', 'meat', 'seeds', 'garbage'] 
} 

def generate_sentence(choice_of_dict): 
    return ' '.join(random.choice(choice_of_dict[i]) for i in range(len(choice_of_dict))) 

generate_sentence(d_1) 
>> 'She hates Chevys' 
generate_sentence(d_2) 
>> 'Dogs hate tuna' 
1

一件事,可能帮助你在这里是使用嵌套列表来描述这些句子,然后有产生给出了这样一个随机句子的功能一个嵌套列表;这可能是这样做的一种方式。

truck_preferences = [['I', 'she', 'he'], ['loves', 'hates', 'likes'], ['chevys', 'fords', 'rams']] 
animal_foods=['dogs', 'cats', 'birds'], ['love', 'hates'], ['tuna', 'meat', 'seeds', 'garbage'] 

def random_sentence(nested_list): 
    words=[random.choice(sublist) for sublist in nested_list] 
    return " ".join(words) 
相关问题