2016-05-03 30 views
3

我有一个词典列表。为什么比较空值不起作用?

students = [{"id":''},{"id":1},{"id":3}] 

我正在遍历这个并寻找字典,其中id不是''

这是我曾尝试:

for student in students: 
    if(student['id'] is not None or student['id'] != ''): 
     print("found student" + str(student['id'])) 
     break 

但无论怎样,它总是那张if块内。任何指针在比较空值时有什么错误?

+4

这不应该是一个“和”? –

+0

啊!那真是很愚蠢:)我删除了第一个条件'if(student ['id']!='')'this enough!谢谢 – aaj

回答

4

什么之前:

if student['id'] not in (None, ''): 
    # do someting 
3
student['id'] is not None or student['id'] != '' 
  • 如果该值实际上是None,第二条件将是如此,因为None不等于''

  • 如果该值为空,则第一个条件将为真,因为空不是None

作为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 
0
if(person is not theif or person is not king): 
    kings and theif are both allowed into the closure. 
    as kings are not thief and thief are not king. 

or操作仅需要one true condition才能满足。一件东西只有一种类型。

One type will always not be at least one two different things. 
+0

虽然这段代码可能会回答这个问题,但提供关于为什么和/或如何回答问题的附加背景将显着提高其长期价值。请[编辑]你的答案,添加一些解释。 – CodeMouse92