Python 如果在for循环下工作!=但是==

Python 如果在for循环下工作!=但是==,python,python-2.7,python-3.x,if-statement,namedtuple,Python,Python 2.7,Python 3.x,If Statement,Namedtuple,我不明白为什么==条件不起作用,但是!=正在为循环工作。以下是代码段: # 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 (stu

我不明白为什么==条件不起作用,但是!=正在为循环工作。以下是代码段:

# 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

您说它意外停止,这是因为for循环中的
返回
,它正在停止循环。摆脱它,它应该会起作用(你可以用
pass
代替它)

资料来源:


要反转条件的逻辑,除了反转比较运算符外,还需要用
替换和
,反之亦然,以及对任何布尔检查求反:

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

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)

因此,如果存在studend id或学生姓名,并且其中一个或两个字段与特色学生(id、姓名)不同,则会将其添加到列表中,对吗?

为什么要添加student\u id和student\u id??为什么不直接执行
student\u id==student.id
确定您不是指
student\u detail.id
student\u detail.name
?每个括号中的第一个检查可能是为了确保没有对
None
对象进行属性访问,以避免异常。如果它确实试图避免这种情况,那么检查应该更加具体:
student\u id不是None,student\u id!=student.id
。我还没有上传完整的编码,student\u id是输入到fn的。我们正在检查文件中保存的数据,如student_detail.id或student。id@tzaman,DeliriousSyntax:是的,你是对的,这是“student_detail.name”,在实际代码中是对的。但是for==条件既不返回正确的值也不存储在列表中。如果这回答了您的问题,请接受此答案!是的,你是绝对正确的,但我必须做的是,检查student_id(给定的输入)是否存在,如果它与student_detail.id匹配(这里有问题,我写错了,但主代码没问题),然后返回它,否则,在列表中添加student_细节(来自循环)。学生的名字也一样。积极的逻辑不起作用,但消极的逻辑。还有一件事,请你在积极的条件下发布,这对我来说不起作用。你必须在每个问题中提出一个具体的问题,而不是“帮助我让整个代码工作”。我回答了你提出的关于这两种情况的区别的具体问题;如果您还有其他问题,请单独发布。是的,但如果条件失败,则不使用退货,对吗?但它还是停止了。既不重新运行正确的值,也不保存在列表中。如果有任何错误,请更正。是的,我们必须检查(id或名称)是否为真,它是否与列表中的值匹配。if matches返回else,并将其添加到列表中。@user5259019同时使用while循环会更具可读性。@user5259019为什么不发布一些示例数据或示例来测试它?