如何让函数在Python中返回多个结果(使用forloops和dictionary)?

2024-04-20 04:48:18 发布

您现在位置: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字符串中的第三个case进行测试时得到的结果:

{'one':1.0}

因此,由于它不返回{three':3.0},我觉得它只返回字典中的一个匹配项,所以可能需要返回一个新字典,这样它就可以遍历所有的情况。你觉得这种方法怎么样?我很新,所以我希望下面的代码有一定的意义,尽管语法错误。我真的试过了。你知道吗

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

return empty

Tags: the方法keyinreturnifpropertyval
2条回答

如果return用于,则该函数将针对该特定调用终止。因此,如果您想返回多个值,这是不可能的。可以改用数组。可以将值存储在数组中并返回数组。你知道吗

您的想法几乎奏效,但(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]

相关问题 更多 >