【问题标题】:can anyone explain the mechanism of working of is operator in list? [duplicate]任何人都可以解释列表中 is 运算符的工作机制吗? [复制]
【发布时间】:2019-08-04 23:08:30
【问题描述】:
l1=[1,2,3]
l2=[1,2,3]
print(l1 is l2)
# False

谁能解释这段代码。为什么是假的?

【问题讨论】:

  • 您可以将其视为实例比较。它是完全相同的对象吗?不仅仅是内容。
  • Python is 总是检查对象身份== 通常检查对象平等

标签: python


【解决方案1】:

is 运算符检查两个操作数是否引用同一个对象。在这个 l1 和 l2 是两个不同的对象,所以,它返回 False。

请注意,两个列表实例不会仅仅因为它们具有相同的内容而引用同一个对象。

您可以使用id 检查两者是否引用同一个对象。检查下面的代码。在这种情况下,您可以看到l1l2 是不同的对象,而l2l3 指的是同一个对象。请注意以下代码中== 运算符的使用以及如果列表的内容相同,它如何返回True

l1=[1,2,3]
l2=[1,2,3]
l3 = l2
print("l1 = %s" %(id(l1)))
print("l2 = %s" %(id(l2)))
print("l3 = %s" %(id(l3)))
print(l1 is l2)
print(l2 is l3)
print(l1 == l2)
print(l2 == l3)

输出:

l1 = 139839807952728
l2 = 139839807953808
l3 = 139839807953808
False
True
True
True

注意:如果要根据内容比较两个对象,请使用== 运算符

【讨论】:

    【解决方案2】:

    is:测试两个变量是否指向同一个对象,而不是两个变量具有相同的值。

    Nicely put:

    # - Darling, I want some pudding!
    # - There is some in the fridge.
    
    pudding_to_eat = fridge_pudding
    pudding_to_eat is fridge_pudding
    # => True
    
    # - Honey, what's with all the dirty dishes?
    # - I wanted to eat pudding so I made some. Sorry about the mess, Darling.
    # - But there was already some in the fridge.
    
    pudding_to_eat = make_pudding(ingredients)
    pudding_to_eat is fridge_pudding
    # => False
    

    【讨论】:

      【解决方案3】:

      所以== 运算符比较两个对象或变量的值,is 运算符检查比较的对象是否相同。你可以把它想象成比较pointers

      【讨论】:

        猜你喜欢
        • 2011-04-05
        • 2016-01-14
        • 2019-06-02
        • 1970-01-01
        • 1970-01-01
        • 2011-03-31
        • 1970-01-01
        • 2017-05-09
        • 2011-02-28
        相关资源
        最近更新 更多