从python中的用户输入列表中提取随机项

时间:2013-01-30 03:55:58

标签: python list input user-input

sup = ['eyes', 'nose', 'mouth'] 
car = ['4wd', 'hatch', 'coupe']
tan = ['dark', 'light', 'pale']

objects = ['sup', 'car', 'tan']

import random

print 'choose 2 objects from the following list separated by commas:'
print 'sup, car, tan'

chorol []
chorol.extend (objects[:2])

from random import choice
print choice (1)

from random import choice
print choice (2)

我试图让用户从一组3中选择2个列表,然后从用户选择的2个列表中的每个列表中打印1个随机项。我最近才开始学习编码,所以错误可能非常基本。

1 个答案:

答案 0 :(得分:2)

你最好使用字典:

import random
d = dict(sup = ['eyes', 'nose', 'mouth'],
         car = ['4wd', 'hatch', 'coupe'],
         tan = ['dark', 'light', 'pale'])

items = raw_input("pick 2 (separated by comma):" + ','.join(d)+' > ')
#The next line of code could be
#item1,item2 = [x.strip() for x in items.split(',')] 
#if you want to do some validation
item1, item2 = items.split(',')  

print 'picked:', random.choice(d[item1])
print 'picked:', random.choice(d[item2])