if if for for循环工作!=但==

时间:2015-12-03 16:14:21

标签: python python-2.7 python-3.x if-statement namedtuple

我不明白为什么==条件不起作用但是!=正在进行for循环。这是代码段:

# this way it's not working . only single time running and not giving desired output

list_of_student= []

for student in student_list:

    student_detail = student(val[1],val[2],val[3])  # namedtuple

    if (student_id and student_id==student.id) or (student_name and student_name==student.name):
        return student_detail
    else:
        list_of_student.append(student_detail)

但是,如果我将==更改为!=并恢复以下操作,它的工作正常。 你能告诉我原因,或者我错在哪里吗?

#this way it's working fine.
list_of_student= []

for student in student_list:

    student_detail = student(val[1],val[2],val[3])   # namedtuple
    if (student_id and student_id!=student.id) or (student_name and student_name!=student.name):
        list_of_student.append(student_detail)

    else:
        return student_detail

3 个答案:

答案 0 :(得分:3)

要反转条件的逻辑,除了反转比较运算符之外,还需要将and替换为or,反之亦然,以及否定任何布尔检查:< / p>

if ((not student_id) or student_id != student.id) and ((not student_name) or student_name != student.name):

答案 1 :(得分:0)

你说它意外停止了,这是因为你的for循环中的return,它正在停止循环。摆脱它,它应该工作(你可以用pass替换它。)

  

来源:   return statement in for loops

答案 2 :(得分:-1)

None值比较,

list_of_student= []

for student in student_list:

    student_detail = student(val[1],val[2],val[3])  # namedtuple

    if (student_id != None and student_id==student.id) or (student_name != None and student_name==student.name):
        return student_detail
    else:
        list_of_student.append(student_detail)

因此,如果存在studentnd id或学生姓名,并且一个或两个字段与特色学生(id,name)不同,那么会被添加到列表中,对吗?