为什么比较空值不起作用?

时间:2016-05-03 17:25:31

标签: python dictionary

我有一个词典列表。

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区块。任何指针在比较空白值时有什么问题?

3 个答案:

答案 0 :(得分:4)

怎么样:

if student['id'] not in (None, ''):
    # do someting

答案 1 :(得分:3)

student['id'] is not None or student['id'] != ''
  • 如果该值实际为None,则第二个条件为真,因为None不等于''

  • 如果值为空,则第一个条件为true,因为空为None

由于or运算符要求至少有一个表达式为Truthy,因此整个表达式始终为True。这就是为什么控件总是进入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

答案 2 :(得分: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.