簡體   English   中英

使用Python字典值返回鍵作為結果

[英]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。

  • catch_speeding(60,假)→0
  • catch_speeding(65,False)→1
  • catch_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]

問題不認為生日詞典具有更高的可用值嗎?

如果這是我的生日,我要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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM