2015-04-06 98 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}