[英]Function call inside a loop python
I do have following problem - 我确实有以下问题-
dict1 = {'abc': {'x': 2, 'y': 3, 'z': 4}, 'mno': {'p': 3, 'q':4, 'r':5}}
def refine():
def calc(a_dict):
if some_condition :
return x ={'a':1}
else:
return None
for k, v in dict1:
return calc(v)
Now when I am iterating
this function call inside a for loop , I get either None
or a
. 现在,当我在for循环中
iterating
此函数调用时,得到None
或a
。 The function call is such that I can get maximum of one a
. 函数调用使我最多可以得到一个
a
。
Sample Output - 样本输出 -
None
None
{'a':1}
None
What I want calc
function to return None
in case all the values after the loop gives None
or x
in case any of the values after loop gives x
.How can this be achieved ? 我想
calc
函数返回None
循环后,所有的值的情况下,给出了None
或x
的情况下,任何一个值后循环使x
。如何才能实现这一目标? Thanks in advance. 提前致谢。
Edit - What if I store the results in a list and want to check if the list has something else than None
and if True
return it. 编辑 -如果我将结果存储在列表中并且要检查列表中是否包含除
None
以外的其他内容,以及if True
返回它,该怎么办?
If I did get the question, you may store results of conditions applied on a dictionary and then check with all
quantifier function: 如果确实收到问题,则可以存储应用于字典的条件结果,然后使用
all
量词功能进行检查:
def calc(a_dict):
results = (some_condition(k,v) for k,v in a_dict.iteritems())
if all(res == None for res in results):
return None
elif all(res == <something> for res in results):
return {'a':1}
else:
return <something different>
u can use any() . 您可以使用any()。 any check for the condition if any one value is true.
任何条件是否为真的任何检查。 it return x .
它返回x。 if all values fail it goes to else
如果所有值都失败,则转到其他值
if any(somecondition):
return x
else:
return None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.