我不明白为什么==条件不起作用但是!=正在进行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
答案 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
替换它。)
答案 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)不同,那么会被添加到列表中,对吗?