![](/img/trans.png)
[英]How do I use Python for-loops to get my program to return the right values?
[英]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.