Python:!= 和“is not”之间的区别
我不清楚语法 !=
和 is not
之间的区别。它们似乎做了同样的事情:
>>> s = 'a'
>>> s != 'a'
False
>>> s is not 'a'
False
但是,当我在列表理解中使用 is not
时,它会产生与使用 !=
不同的结果。
>>> 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']
为什么 o
包含在第一个列表中,而不是第二个列表中?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
is
测试对象身份,但==
测试对象值相等:is
tests for object identity, but==
tests for object value equality:is not
比较引用。==
比较值is not
compares references.==
compares values根据您的困惑程度,这可能会有所帮助。
这些语句是相同的:
Depending on how you were confused, this might help.
These statements are the same:
我想补充一点,他们绝对不会做同样的事情。
我会用!=。
例如,如果你有一个 unicode 字符串......
使用 !=,Python 基本上会执行从 str() 到 unicode() 的隐式转换并比较它们,而使用 is 则不会,如果它是完全相同的实例,则它会匹配。
I'd like to add that they definitely do not do the same thing.
I would use !=.
For instance if you have a unicode string....
With !=, Python basically performs an implicit conversion from str() to unicode() and compares them, whereas with is not, it matches if it is exactly the same instance.
我只是引用参考资料
is
测试操作数是否相同,可能引用同一个对象。其中!=
测试该值。这是一个不定循环,因为对象 s 永远不等于 [] 所引用的对象,它引用的是一个完全不同的对象。其中,用
s != []
替换条件将使循环确定,因为这里我们正在比较值,当 s 中的所有值都弹出后,剩下的就是一个空列表。I am just quoting from reference,
is
tests whether operands are one and same, probably referring to the same object. where as!=
tests for the value.this is a indefinite loop, because object s is never equal to an object reference by [], it refers to a completely different object. where as replacing the condition with
s != []
will make the loop definite, because here we are comparing values, when all the values in s are pop'd out what remains is a empty list.