2015-04-06 94 views
0
people = { 
    'Thomas' : 'Asian and sly', 
    'Kota' : 'Mature and carefree', 
    'Seira' : 'Talented and honest', 
    'Rika' : 'Energetic and Adventurous', 
    'Josh' : 'Mysterious and bluntly honest', 
    'Mizuho' : 'Cute and friendly', 
    'Daniel' : 'Funny and smart' 
} 



def qualities(): 
    print "There are five of my friends. Which one would you like to know  about?" 
    print """ 
1. Thomas 
2. Kota 
3. Seira 
4. Rika 
5. Josh 
6. Mizuho 
7. Daniel 
""" 

person = raw_input ('> ') 

if "Thomas" in person or "thomas" in person or "1" in person: 

    print "Thomas is : ", people['Thomas'] 

elif "Kota" in person or "kota" in person or "2" in person: 
    print "Kota is : ", people['Kota'] 

elif "Seira" in person or "seira" in person or "3" in person: 
    print "Seira is : ", people['Seira'] 

elif "Rika" in person or "rika" in person or "4" in person: 
    print "Rika is : ", people['Rika'] 

elif "Josh" in person or "josh" in person or "5" in person: 
    print "Josh is : ", people['Josh'] 

elif "Mizuho" in person or "mizuho" in person or "6" in person: 
    print "Mizuho is : ", people['Mizuho'] 

elif "Daniel" in person or "daniel" in person or "7" in person: 
    print "Daniel is : ", people['Kota'] 

else: 
    print "Please choose a friend of mine." 
    qualities() 

qualities() 

此代码要求输入他们想知道的朋友,然后吐出“人物”中定义的品质。我只想知道这是否是执行此类程序的最有效方式,因为输入用户可能会进入提示的所有条件是很乏味的。缩短功能以减少重复性

回答

0

一个suggestion.You可以使用此

mylist = ["Thomas", "thomas", "1"] 
if any(i in person for i in mylist): 
    print "Thomas is : ", people['Thomas'] 
2

你说得对,以尽量减少,尤其是信息重复。该功能可能类似:

def qualities(): 
    while True: 
     names = people.keys() 
     for index, name in enumerate(names, 1): 
      print '{}: {}'.format(index, name.capitalize) 
     person = raw_input(' > ').lower() 
     if person in names: 
      print people[person] 
      break 
     elif person.isdigit() and int(person) - 1 in range(len(names)): 
      print people[names[int(person)-1]] 
      break 
     else: 
      print 'Please enter a name or number.' 

注意,在people名键应该是全部小写的这个工作。我也使用了while循环而不是递归来实现它。


由于词典是一种无序数据结构,名称可能出来以不同的顺序,以你所期望的一个。如果顺序很重要,考虑二元组(name, description)的列表:

people = [ 
    ('Thomas', 'Asian and sly'), 
    ... 
] 

这将保留您想要的顺序。您可以随时在运行时为其建立字典以便快速访问名称:

named_people = {name: description for (name, description) in people}