Python:!= 和“不是"之间的区别 [英] Python: Difference between != and "is not"

查看:38
本文介绍了Python:!= 和“不是"之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不清楚语法 !=is not 之间的区别.他们似乎在做同样的事情:

<预><代码>>>>s = 'a'>>>s != 'a'错误的>>>s 不是 'a'错误的

但是,当我在列表推导式中使用 is not 时,它产生的结果与使用 != 时产生的结果不同.

<预><代码>>>>s = "你好">>>[c for c in s 如果 c 不是 'o']['你好']>>>[c for c in s if c !='o']['地狱']

为什么 o 包含在第一个列表中,而不包含在第二个列表中?

解决方案

is 测试对象身份,但 == 测试对象值相等性:

在[1]中:a = 3424在 [2] 中:b = 3424在 [3] 中:a 是 b出[3]:假在[4]中:a == b输出[4]:真

I'm unclear about the difference between the syntax != and is not. They appear to do the same thing:

>>> s = 'a'
>>> s != 'a'
False
>>> s is not 'a'
False

But, when I use is not in a list comprehension, it produces a different result than if I use !=.

>>> s = "hello"
>>> [c for c in s if c is not 'o']
['h', 'e', 'l', 'l', 'o']
>>> [c for c in s if c != 'o']
['h', 'e', 'l', 'l']

Why did the o get included in the first list, but not the second list?

解决方案

is tests for object identity, but == tests for object value equality:

In [1]: a = 3424
In [2]: b = 3424

In [3]: a is b
Out[3]: False

In [4]: a == b
Out[4]: True

这篇关于Python:!= 和“不是"之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆