重构if语句

时间:2018-08-24 13:59:36

标签: python

if a not in list and a == b:
    //add to list
    //do stuff in For Loop
    return True  
elif a in list and not a == b:
    //add to session
    //do stuff in For Loop
    return True
elif a in list and a == b:
    //do stuff in For Loop
    return True
elif a not in list
    //add to list
    //add to session
    return True        
else:
   return 

For循环中的// do东西是在3个if语句中重复的相同代码

2 个答案:

答案 0 :(得分:1)

我建议您采用我的解决方案,将动作“添加到列表” “添加到会话” “执行任务” 与原始代码的顺序相同。我还考虑过可以将这些动作替换为示例中的print()语句,如下所示:

def func():
    if a not in a_list:
        print("add to list")

    if a != b:
        print("add to session")

    if (a == b) or (a in a_list):
        print("do stuff")

    return True

注意:在python中,注释行以#字符开头,而不是//

答案 1 :(得分:0)

if a in lst or a == b:
    # Do stuff

if a != b :
    # add to session

if a not in lst :  # have to be at the end since it modify the list
    # add to lst

return True