python - if else 在 for 循环下工作 != but ==

标签 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

最佳答案

要反转条件的逻辑,您还需要将 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/

相关文章:

python - 当类的 __init__ 需要参数时构造不带参数的对象(矩形)

python - 如何在Python2中循环遍历\u2190-\u21FF的范围

python - 验证错误 : Redefined outer name from outer scope

python - 数据文件夹应该如何在 cnn 模型中将输入作为 (x-train, y-train), (x-test, y-test)

javascript - heroku 不在 https 上加载 jquery

Python:脚本的目录

python - OpenId 连接提供商 Python 3

Python 多重处理和序列化数据

python - 从兄弟目录导入的问题

python - 为什么我在python3中的代码测试无法通过?