Python strings references
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Python '==' vs 'is' comparing strings, 'is' fails sometimes, why?
你好。我有一个问题,当涉及到如何以及何时使用引用时,Python是如何工作的。
我有一个我理解的例子。
1 2 3 4 | a ="cat" b = a a is b True |
这是有道理的。但有件事我不明白。
1 2 3 4 5 6 7 8 9 10 11 12 | a ="cat" b ="cat" a is b True c = 1.2 d = 1.2 c is d False e ="cat" f ="".join(a) e is f False |
为什么A是B是真的而不是C是D?这两种类型都是不变的,对吗?它在使用浮点数时起作用我只能想象它是某种优化,但我很乐意得到任何答案。
我还尝试了其他一些方法,结果是:
1 2 3 4 5 6 7 8 9 10 11 | a ="cat" b ="c" c = b+"at" a is c False # Why not same as setting c ="cat" d ="cat"+"" a is d True # Probably same as setting d ="cat" e ="c"+"at" a is e True # Probably same as setting e ="cat" |
我想这里的问题是一样的,但是为什么当变量b被用来创建"cat"时它不给出真值呢?
我使用python 2.5,如果这会有什么不同的话。
这里有任何有用的建议和想法都会受到赞赏。
字母名称布尔奇1(P)Well,the correct question would be"Why does EDOCX1 penal 0 return EDOCX1 commercial 1 commercial and not EDOCX1 commercial 2?"从逻辑上讲,行为的预期将是返回字母名称1-它们是分开的目标,在分离的地方产生。(p)(P)Thing is,the current implementation of python written in C,CPYTHON,uses string and small int catching as a means of最优化.The logic behind that最优化is that,since they're imputable anyway,it should't matter.但是,你不应该仅仅因为行为是执行——具体而不是语言的一部分。总是使用EDOCX1,音标4比较脱衣,而不是EDOCX1,音标5。EDOCX1 Also has an最优化for immutable builtin types,where it checks identity first,and only if they aren't the same object,proceeds with the equality test.So it shouldn't matter performance-wise.(p)(P)Looks like you've already found why you can't rely on it on cython itself,on the rest of your question.(p)