簡體   English   中英

Python函數未返回正確的輸出

[英]Python function not returning correct output

嘗試使用python更改與字典中的鍵相關聯的值,並且未返回正確的輸出

def fetchAndReplace(dictionary,key,newValue):
    keys = dictionary.keys()
    for i in keys:
        if i == key:
            print dictionary[key]
            dictionary[key] = newValue
            return

        else: 
            return "Nothing"

當我稱其為字典{'x':3,'y':2}時,x代表鍵,6代表newValue,它不返回字符串,也不應該返回。 我的代碼找不到任何錯誤,因此,如果您能指出我忽略的錯誤,我將不勝感激。

問題是您要在第一次迭代中return ,因此您永遠都不會到達第二個鍵。

嘗試這個:

def fetchAndReplace(dictionary, key,newValue):
    keys = dictionary.keys()
    for i in keys:
        if i == key:
            dictionary[key] = newValue

    return dictionary



print fetchAndReplace({'x':3,'y':2}, 'x', 6)

輸出:

{'y': 2, 'x': 6}

此外,您可以使用dict.update方法完成與您的功能相同的操作:

>>> mydict = {'x':3,'y':2}
>>> mydict.update({'x': 6})
>>> print mydict
{'y': 2, 'x': 6}

心連心,
亞倫

認為您正在嘗試按照以下方式進行操作:

def fetchAndReplace(dictionary,key,newValue):
    if key in dictionary:
        dictionary[key]=newValue
        return dictionary
    else:
        return 'Nothing' 

di=  {'x':3,'y':2}

print fetchAndReplace(di, 'z', 6)    
print fetchAndReplace(di, 'x', 6)

打印:

Nothing
{'y': 2, 'x': 6}

打印聲明總是有幫助的

def fetchAndReplace(dictionary,key,newValue):
    keys = dictionary.keys()
    print 'keys:', keys
    for i in keys:
        print 'i:', i, 'i == key:', i == key
        if i == key:
            print dictionary[key]
            dictionary[key] = newValue
            return

        else: 
            return "Nothing"

字典中的項目幾乎是任意排序的 ,如果條件語句if i == key失敗,並且鍵中的第一個項目失敗,則該函數將返回

我很想回答這個問題。

您只需刪除兩個制表符(或8,如果使用空格)即可使代碼正常工作。

減少else:的縮進else: return "Nothing"

結果:

def fetchAndReplace(dictionary, key, newValue):
    keys = dictionary.keys()
    for i in keys:
        if i == key:
            print dictionary[key]
            dictionary[key] = newValue
            return
    else:
        return "Nothing"

dictionary = {"x":1, "y":2}
print "The result is: " + str(fetchAndReplace(dictionary,"x",3))
print "The result is: " + str(fetchAndReplace(dictionary,"z",0))

這將產生:

1
The result is: None
The result is: Nothing

為什么? 因為通過減少縮進量, else將附加到for ,並且根據本文檔 ,僅當for循環正常退出時(即,沒有breakreturn ),才會執行for..elseelse部分。它會遍歷所有條目,並且只有在沒有找到鍵的情況下,它才會返回字符串“ Nothing”。 否則,它將返回None ,因為您只有語句return

但是正如其他人所注意到的,您可能想要這樣的東西:

def fetchAndReplace(dictionary, key, newValue):
    result = dictionary.get(key, "Nothing")
    dictionary[key] = newValue
    return result

哪種邏輯是將dictionary[key]的原始值保存到變量result ,如果該鍵不可用,則將為其分配值Nothing 然后,將您的鍵的值替換為dictionary[key] = newValue ,然后返回result

運行此代碼:

dictionary = {"x":1, "y":2}
print "The result is: " + fetchAndReplace(dictionary,"x",3)
print "The result is: " + fetchAndReplace(dictionary,"z",0)

將產生

The result is: 1
The result is: Nothing

似乎您想計划沒有字典的情況。 但是,您已經創建了一個。 拿走退貨一無所有。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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