python字典进行大写转化_Python字典转换成小写?
基本上比較一個小寫版本的響應與小寫版本的正確答案。在
但有幾件事在你的問題中并不完全清楚:
你到底在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]中的每一項。在
總結
以上是生活随笔為你收集整理的python字典进行大写转化_Python字典转换成小写?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot 设置ico_Spr
- 下一篇: linux将字符串转小写_小猿圈总结Li