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 :(得分: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}
答案 1 :(得分:0)
一个建议。你可以使用这个
mylist = ["Thomas", "thomas", "1"]
if any(i in person for i in mylist):
print "Thomas is : ", people['Thomas']