Python 能够在输入中使用任意大小写,在输出中生成相同的dict值
我有以下代码:Python 能够在输入中使用任意大小写,在输出中生成相同的dict值,python,dictionary,case,Python,Dictionary,Case,我有以下代码: people = {'Bob' : {'phone' : '12', 'birthday' : 'May', 'address' : 'ABC', 'interests' : ['a', 'b', 'c']}, 'Mary' : {'phone' : '13', 'birthday' : 'April', 'address' : 'CBA',
people = {'Bob' : {'phone' : '12',
'birthday' : 'May',
'address' : 'ABC',
'interests' : ['a', 'b', 'c']},
'Mary' : {'phone' : '13',
'birthday' : 'April',
'address' : 'CBA',
'interests' : ['d', 'e', 'f']},
response = ['']
wrong = "I don't know. Try again or type 'quit' to get out: "
while response[0] != 'quit':
response = raw_input("Please enter who you're looking for, or type 'quit' to get out: ").split()
try:
print "%s's %s is %s" % (response[0], response[1], people[response[0]][response[1]])
except KeyError:
print wrong,
我想让它在任何情况下都可以输入,并且仍然生成正确的输出。
例如
全力以赴
Mary's phone number is 13.
您应该使用
capitalize()
和lower()
如果您走这条路线,您应该将'bob'
键更改为'bob'
或者,如果重用结果,您可以节省更多的CPU周期,如下面的rubik所述
while response[0] != 'quit':
response = raw_input("Please enter who you're looking for, or type 'exit' to quit the program: ").split()
try:
fn, thing = response[0].capitalize(), response[1].lower()
print "%s's %s is %s" % (fn, thing, people[fn][thing])
except KeyError:
print wrong,
您应该使用
capitalize()
和lower()
如果您走这条路线,您应该将'bob'
键更改为'bob'
或者,如果重用结果,您可以节省更多的CPU周期,如下面的rubik所述
while response[0] != 'quit':
response = raw_input("Please enter who you're looking for, or type 'exit' to quit the program: ").split()
try:
fn, thing = response[0].capitalize(), response[1].lower()
print "%s's %s is %s" % (fn, thing, people[fn][thing])
except KeyError:
print wrong,
通过使用
str.lower()
将输入转换为小写,尝试确保输入始终为小写。然后确保所有的人名{}
都是小写的,以便于搜索,并在输出时将输出重新格式化为大写名称。尝试通过使用str.lower()
将输入转换为小写,确保输入始终是小写的。然后确保你所有的people{}
姓名都是小写的,以便于搜索,并在输出时将输出格式化为大写名称。这个问题的问题是,在people
dictoops中,玛丽的电话号码是13-我的错误。刚刚为这篇文章现场制作了“输出”。谢谢你指出!这些名字是否都大写Mary
大写,bob
不是…@FerdinandBeyer我甚至不知道它的存在!从现在开始,我将:)这个问题的问题是玛丽的电话号码是13在人口述-我的错误。刚刚为这篇文章现场制作了“输出”。谢谢你指出!这些名字是否都大写Mary
大写,bob
不是…@FerdinandBeyer我甚至不知道它的存在!从现在开始,我将:)为什么不将response[0]。大写()
和response[1]。由于您多次使用它,所以将其降低()
。@rubik,这是CPU周期的增量节约,但我试图使答案尽可能与原始答案平行。@MikePennington:我不认为节省CPU周期是一个问题,我的建议只是为了可读性。为什么不将response[0]。大写()
和response[1]。lower()
分配给一些变量,因为您多次使用它?@rubik,这是CPU周期的增量节省,但我试图使答案尽可能与原始答案平行。@MikePennington:我不认为节省CPU周期是一个问题,我的建议只是为了可读性。
while response[0] != 'quit':
response = raw_input("Please enter who you're looking for, or type 'exit' to quit the program: ").split()
try:
fn, thing = response[0].capitalize(), response[1].lower()
print "%s's %s is %s" % (fn, thing, people[fn][thing])
except KeyError:
print wrong,