简体   繁体   English

循环内部的python调用函数和函数包含if else结构

[英]python call function inside for loop and function contain if else structure

I have the following python code that call a function that iterate over a dict.我有以下 python 代码调用一个迭代字典的函数。 the code below not work as expected:下面的代码没有按预期工作:

list1=["test1","test2","test3","test4"]
list2=["toto1","test1","test3","toto4"]

def functest(t):
    for l in list2:
        if t == l:
            return cond1
        else:
            return "rien"

for t in list1:
    titi=functest(t)
    print titi

When I print titi var I have toto1 printed 4 times.当我打印 titi var 时,我必须打印 4 次 toto1。

If I remove the else inside my function the code seem to work.如果我删除函数中的 else 代码似乎可以工作。

How you can explain this behavior ?你如何解释这种行为?

Why when I add else with a returned string only the string is printed.为什么当我用返回的字符串添加 else 时只打印字符串。

thanks谢谢

Because return exits the function and returns your program back to the loop.因为return退出函数并将您的程序返回到循环。 So when you add the else statement within the loop, the current element of list1 is compared against 'toto1' , enters the else statement, and the function returns "rien" .因此,当您在循环中添加else语句时,将list1的当前元素与'toto1'进行比较,进入else语句,并且该函数返回"rien"

def functest(t):
    for l in list2:
        if t == l: 
            return cond1
        else:
            return "rien" # we always end up here on the first iteration, 
                          # when comparing against "toto1"

When you remove the else statement, you loop until you find a match in list2 .当您删除else语句时,您将循环直到list2找到匹配项。 However, assuming you still want to return "rien" given that none of the elements in list2 match the element in list1 which is being checked, you should move the return statement out of the loop, so that it is only returned after checking all elements.但是,假设您仍然想返回"rien"因为list2中的元素都不匹配正在检查的list1中的元素,您应该将 return 语句移出循环,以便它仅在检查所有元素后返回.

def functest(t):
    for l in list2:
        if t == l:
            return "match found"
    return "rien"

Demo演示

>>> for t in list1:
       titi=functest(t)
       print (titi)

match found
rien
match found
rien

I have tried to modify code in order to implement your logic.我试图修改代码以实现您的逻辑。

list1=["test1","test2","test3","test4"]
list2=["toto1","test1","test3","toto4"]

def functest(t):
  newReturnList=[]
  for l in list2:
     if t == l:
        newReturnList.append(t+'-found') 
     else:
        newReturnList.append(t+'-NOT found')

return newReturnList


for t in list1:
    titi=functest(t)
   print (titi)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM