![](/img/trans.png)
[英]Python - Return the dictionary key comparing dictionary values with list
[英]Using Python dictionary values to return key as result
我不确定为什么这段代码在输入中失败了(从CodingBat,链接到问题: Exercise Link )。 问题的详细信息在下面, if elif
语句,我可能会执行此问题,但是我想使用字典。 另外,我读到,不建议从字典中获取键值,如下所示。 但是,如果可以指出以下程序中的问题,我将不胜感激。
您开得太快了,警察阻止了您。 编写代码以计算结果,并将其编码为一个int值:0 =无票据,1 =小票据,2 =大票据。 如果速度等于或小于60,则结果为0。如果速度介于61和80之间(含端点),则结果为1。如果速度等于或大于81,则结果为2。除非是您的生日-那天,您的在所有情况下,速度都可以提高5。
def caught_speeding(speed, is_birthday): Bir_dict = {0:speed<=60,1:61<=speed<=80,2:speed>=81} NoBir_dict = {0:speed<=65,1:66<=speed<=85,2:speed>=86} def getKey(dict,value): return [key for key in dict.keys() if (dict[key] == value)] if is_birthday: out1=getKey(Bir_dict,True) return out1[0] else: out2=getKey(NoBir_dict,True) return out2[0]
程序失败
caught_speeding(65, False)
caught_speeding(65, True)
并为
caught_speeding(70, False)
caught_speeding(75, False)
caught_speeding(75, True)
caught_speeding(40, False)
caught_speeding(40, True)
caught_speeding(90, False)
caught_speeding(60, False)
caught_speeding(80, False)
看起来您混合了Bir_dict
和NoBir_dict
。 您可以尝试以下代码吗?
def caught_speeding(speed, is_birthday):
Bir_dict = {0:speed<=65,1:66<=speed<=85,2:speed>=86}
NoBir_dict = {0:speed<=60,1:61<=speed<=80,2:speed>=81}
def getKey(dict,value):
return [key for key in dict.keys() if (dict[key] == value)]
if is_birthday:
out1=getKey(Bir_dict,True)
return out1[0]
else:
out2=getKey(NoBir_dict,True)
return out2[0]
尽管有效,我还是可以建议使用字典的另一种方法:票证定义不会互相干扰,换句话说,词典中只能有一个True
语句。 因此,您可以将代码修改为:
def caught_speeding(speed, is_birthday):
Bir_dict = {0:speed<=65,1:66<=speed<=85,2:speed>=86}
NoBir_dict = {0:speed<=60,1:61<=speed<=80,2:speed>=81}
def getKey(dict):
return [key for key in dict.keys() if (dict[key] == True)]
if is_birthday:
out1=getKey(Bir_dict)
return out1[0]
else:
out2=getKey(NoBir_dict)
return out2[0]
问题不认为生日词典具有更高的可用值吗?
如果这是我的生日,我要65岁了:我希望没有机票。 但是,如果生成字典并打印它们,则可以看到情况并非如此:
def caught_speeding(speed, is_birthday):
Bir_dict = {0:speed<=60,1:61<=speed<=80,2:speed>=81}
print Bir_dict
NoBir_dict = {0:speed<=65,1:66<=speed<=85,2:speed>=86}
print NoBir_dict
def getKey(dict,value):
return [key for key in dict.keys() if (dict[key] == value)]
if is_birthday:
out1=getKey(Bir_dict,True)
return out1[0]
else:
out2=getKey(NoBir_dict,True)
return out2[0]
输出:
{0: False, 1: True, 2: False}
{0: True, 1: False, 2: False}
0
{0: False, 1: True, 2: False}
{0: True, 1: False, 2: False}
1
您只需在字典对象中交叉值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.