student['id'] is not None or student['id'] != ''
作为or
操作者需要的表达中的至少一个是Truthy,这整个表达式将是真总是。这就是为什么控制总是输入if
块。
您可以在这里使用De Morgan's laws。
"not (A and B)" is the same as "(not A) or (not B)"
also,
"not (A or B)" is the same as "(not A) and (not B)".
你想要的ID为 “不无” 和 “非空”,所以你可以写一样,
if student['id'] is not None and student['id'] != '':
# print details
或
if not (student['id'] is None or student['id'] == ''):
# print details
相反,我会推荐使用相同的惯用方式,像这样
for student in students:
if student['id']:
# print details
现在,如果值为None
或为空,则if
语句将跳过当前对象。只有在id
是Truthy值时它才会打印详细信息。
你甚至可以检查id
存在于词典中所获得的价值,这样
for student in students:
if 'id' in student and student['id']:
# print details
这不应该是一个“和”? –
啊!那真是很愚蠢:)我删除了第一个条件'if(student ['id']!='')'this enough!谢谢 – aaj