簡體   English   中英

我如何在Python中讓函數返回不止1個結果(帶有for循環和字典)?

[英]How can I get my function to return more than 1 result (with for-loops and dictionaries) in Python?

我試圖找到一種方法來為我的Python字典返回多個結果:

def transitive_property(d1, d2):
    '''
    Return a new dictionary in which the keys are from d1 and the values are from d2. 
    A key-value pair should be included only if the value associated with a key in d1
    is a key in d2.  

    >>> transitive_property({'one':1, 'two':2}, {1:1.0})
    {'one':1.0}
    >>> transitive_property({'one':1, 'two':2}, {3:3.0})
    {}
    >>> transitive_property({'one':1, 'two':2, 'three':3}, {1:1.0, 3:3.0})
    {'one':1.0}
    {'three': 3.0}
    '''
    for key, val in d1.items():
        if val in d2:
            return {key:d2[val]}
        else:
            return {}

我想出了很多不同的東西,但是它們永遠不會通過一些測試用例,例如第三個(用{'three':3})。 當我在doc字符串中使用第三種情況進行測試時,結果如下:

{'一個':1.0}

因此,由於它不返回{'three':3.0},所以我認為它只返回字典中的一個單例,因此可能是返回一個新字典的問題,以便可以遍歷所有情況。 您會對這種方法說些什么? 我很新,所以我希望下面的代碼盡管存在語法錯誤,還是可以理解的。 我確實嘗試過。

empty = {}
for key, val in d1.items():
    if val in d2:
        return empty += key, d2[val]

return empty

如果使用return,則該函數將針對該特定調用終止。 因此,如果您想返回多個值,那是不可能的。 您可以改用數組。您可以將值存儲在array中,然后將返回值存儲在array中。

您的想法幾乎可行,但是(i)您立即返回了該值,這時該函數退出了;(ii)您無法使用+=將屬性添加到字典中。 相反,您需要使用dictionary[key] = value設置其屬性。

result = {}
for key, val in d1.items():
    if val in d2:
        result[key] = d2[val]

return result

這也可以更簡潔地寫成字典理解:

def transitive_property(d1, d2):
    return {key: d2[val] for key, val in d1.items() if val in d2}

您也可以讓函數返回字典列表,每個字典中都有一個鍵/值對,盡管我不確定為什么會這樣:

def transitive_property(d1, d2):
    return [{key: d2[val]} for key, val in d1.items() if val in d2]

暫無
暫無

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

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