基本上比较一个小写版本的响应与小写版本的正确答案。在
但有几件事在你的问题中并不完全清楚:
你到底在records中存储了什么?
确认书中应使用哪个国家的名称是。。。在…'里?
您想将用户的响应与有效同义词列表相匹配,对吗?在
如果我要写一个城市流行问答游戏,我可能会做这样的事情:import random
cities = {'Dublin': 'IRL',
'London': 'GBR',
}
country_synonyms = {'GBR': ['United Kingdom',
'GBR',
'UK',
'Great Britain and Northern Island',
'GB',
],
'IRL': ['Republic of Ireland',
'IRL',
'Eire',
]
}
# Pick a random city from our dicts' keys
challenge = random.choice(cities.keys())
# Country code of the correct response, e.g. 'GBR'
correct_cc = cities[challenge]
# Assume the canonical name for a country is first in the list of synonyms
correct_name = country_synonyms[correct_cc][0]
response = raw_input('Which country is %s in? ' % challenge)
# Clean any whitespace
response = response.strip()
lowercase_synonyms = [s.lower() for s in country_synonyms[correct_cc]]
if response.lower() in lowercase_synonyms:
answer = "Yes, %s is in the %s." % (challenge, correct_name)
else:
answer = "Sorry, that's wrong. %s is in the %s." % (challenge, correct_name)
print answer
这条线
^{pr2}$
使用列表理解将列表country_synonyms[correct_cc]中的每个字符串转换为小写。另一种选择是使用map:import string
# ...
lowercase_synonyms = map(string.lower, country_synonyms[correct_cc])
这将把函数string.lower映射到列表country_synonyms[correct_cc]中的每一项。在