我不明白为什么 == 条件不起作用,但 != 在 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
最佳答案
要反转条件的逻辑,您还需要将 and and
替换为 or
,反之亦然,以及否定任何 bool 检查,此外反转比较运算符:
if ((not student_id) or student_id != student.id) and ((not student_name) or student_name != student.name):
关于python - if else 在 for 循环下工作 != but ==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34070889/