python - 使用Python字典值返回键作为结果

标签 python dictionary

我不确定为什么这段代码对于一些输入失败(来自 CodingBat,链接到问题: Exercise Link )。问题详细信息如下,我可能可以使用 if elif 语句来解决这个问题,但我想使用字典。另外,我读到不建议从字典中获取键值,如下所示。但如果能指出下面程序中的问题,我将不胜感激。

你开得太快了,一名警察拦住了你。编写代码来计算结果,编码为 int 值:0=无票,1=小票,2=大票。如果速度为 60 或更低,则结果为 0。如果速度在 61 到 80 之间(含 61 和 80),则结果为 1。如果速度为 81 或更高,则结果为 2。除非是您的生日 - 那天,您的在所有情况下速度都可以提高 5 倍。

  • caught_speeding(60, False) → 0
  • caught_speeding(65, False) → 1
  • caught_speeding(65, True) → 0
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_dictNoBir_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]

关于python - 使用Python字典值返回键作为结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50342165/

相关文章:

python - 参数在传递给函数时从字典中消失

c# - 比较两个字典中的键

python - 将列表的列表转换为字典的字典(Python)

python - "The headers or library files could not be found for jpeg"在 Alpine Linux 上安装 Pillow

python - 手动运行curl "http://bas.company.com:9200/dispatcher/_search?q=_id:832238"通过但通过脚本失败

python - MySQL 并锁定一个表,读取,然后截断

python - 使用不区分大小写的字符串访问 python 字典

python 3 : Searching A Text File Smartly

python - 重建 Pandas 数据框

java - 在java中对 map 进行排序