本文介绍了Python中的字符串比较:是vs. ==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我注意到我写的一个Python脚本是松鼠,并追踪到一个无限循环,其中循环条件而line不是''。在调试器中运行它,事实证明,该行实际上是''。当我把它改为!=''而不是不是'',它工作正常。 此外,通常认为只要使用==默认情况下更好,即使比较int或布尔值吗?我一直喜欢使用'是',因为我发现它更美观和pythonic(这是我怎么陷入这个陷阱...),但我想知道,如果它只是被保留为当你关心找到两个对象具有相同的id。解决方案 不总是。 NaN是一个反例。但通常 ,身份(是)意味着平等( == )。反之亦然:两个不同的对象可以具有相同的值。使用 == 当比较值时,是时比较标识。 比较,但不要依赖它。 布尔值,你不应该做比较。而不是: if x == True:#do something 写: 如果x:#do something 用于与无比较,是无优先于 ==无。 我一直喜欢使用'is',因为我发现它更美观的和pythonic(这是我怎么陷入这个陷阱。 ..),但我想知道是否只是为了保留为你关心找到两个对象具有相同的id。 是的,这就是它的用途。 I noticed a Python script I was writing was acting squirrelly, and traced it to an infinite loop, where the loop condition was while line is not ''. Running through it in the debugger, it turned out that line was in fact ''. When I changed it to !='' rather than is not '', it worked fine. Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values? I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id. 解决方案 Not always. NaN is a counterexample. But usually, identity (is) implies equality (==). The converse is not true: Two distinct objects can have the same value.You use == when comparing values and is when comparing identities.When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is, but don't rely on it.For boolean values, you shouldn't be doing comparisons at all. Instead of:if x == True: # do somethingwrite:if x: # do somethingFor comparing against None, is None is preferred over == None.Yes, that's exactly what it's for. 这篇关于Python中的字符串比较:是vs. ==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-27 16:43