【问题标题】:Why does 'is' operator show different result in Python - 3.6.8?为什么'is'运算符在 Python - 3.6.8 中显示不同的结果?
【发布时间】:2019-08-11 10:56:49
【问题描述】:

参考以下问题 -

1) different run results between python3 and python2 for the same code

2) “is” operator behaves unexpectedly with integers

3)Consecutive 'is' operator in Python [duplicate]

4) Chaining “is” operators

5)What does 'is' operator do in Python?

6) Strange python 'is' operator in arithmetic [duplicate]

7) Why does the “is” keyword have a different behavior when there is a dot in the string?

不重复问题的解释 - 在我的问题中,我没有包含任何符号、数值。我包括简单的字符串。在上面提到的第 7 个问题中,我已经知道给出不同输出的原因,并且我已经阅读过。

在这里,我的问题有所不同。

我的问题描述 -

我正在练习使用 3.6.8 版本的 Python 代码并使用 PyCharm 编辑器。

print('a' * 18 is 'aaaaaaaaaaaaaaaaaa')
print('a' * 19 is 'aaaaaaaaaaaaaaaaaaa')
print('a' * 20 is 'aaaaaaaaaaaaaaaaaaaa')
print('a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa')
print('a' * 22 is 'aaaaaaaaaaaaaaaaaaaaaa')

输出 =

True
True
True
False
False

为什么'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa' 及以后的字符串不会评估为 True? 任何帮助将不胜感激

【问题讨论】:

    标签: python-3.x string pycharm operators


    【解决方案1】:

    为什么'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa' 及以后的字符串不会评估为 True?

    从下图中,倒数第二个源代码编译步骤产生了第一个版本的字节码。这个“原始”字节码最终进入称为“窥孔优化”的最后一个编译步骤。这一步的目标是通过用更快的指令替换一些指令来生成更高效的字节码。

    Reference Image

    在所有 Python 包中都会遇到 .pyc 文件。 Python 字节码存储在这些文件中。如果有人写了这样的 ['foo!'] * 10**9 会发生什么?生成的 .pyc 文件会很大!为了避免这种现象,通过窥孔优化生成的序列如果长度超过 20 则被丢弃。

    因此,在上述问题中,以下给定代码会为长度大于 20 的值生成 False 结果,而不会为值 20 或小于 20 的字符串生成 False .

    print('a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa')
    print('a' * 22 is 'aaaaaaaaaaaaaaaaaaaaaa')
    

    输出 =

    False
    False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 2019-12-02
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      相关资源
      最近更新 更多