【问题标题】:why list and string are behaving differently while checking equality in the below case为什么在以下情况下检查相等性时列表和字符串的行为不同
【发布时间】:2021-02-19 18:39:31
【问题描述】:

为什么相等的行为不同?在 list 的情况下它给出 false 但在 string 的情况下它给出 true 并且在最后一种情况下它是奇怪的 False

list1 = [1, 2, 3]
list2 = list1[:]
print(id(list1))
print(id(list2))
print(list1 is list2)
print(id(list1) == id(list2))

140271225865864
140271225867080
假的
错误

list3="hello"
list4=list3[:]
print(id(list3))
print(id(list4))
print(list3 is list4)

140271226135360
140271226135360
真的

list5="hello"
list6 = ''.join(c for c in list5) 
print(list5 is list6)

错误

【问题讨论】:

  • 由于字符串是不可变的,因此浅拷贝返回相同的对象并不重要,这样可以节省进行真正拷贝的时间。不过,对于列表来说,这很重要,因为它们是可变的。
  • 此外,由于可变性,list1[:] 必须创建一个新列表。由于str 是不可变的,list3[:] 可以返回相同的str,但我不知道有什么说它必须
  • 只是对此的后继怀疑 .. list4 = ''.join(c for c in list3) print(list4 is list3) .. 那么为什么这会给出 False 作为输出,因为这也会创建相同的字符串@schwobaseggl

标签: python python-3.x list


【解决方案1】:

有几种不可变的。字符串是幸运的,python 强制执行 'hello' 的相同副本,在整个代码中的任何地方都使用。所以

s='hello'
#many lines of code
t='hello'
id(t)==id(s)

元组不走运

s=(1,2)
#many lines of code
t=(1,2)
id(t)!=id(s)
#but you do have
hash(t)==hash(s)

List 是可变的,所以可以保证

s=[1,2]
#many lines of code
t=[1,2]
id(t)!=id(s)
#You cannot run hash on mutables
hash(t)==hash(s) #error

【讨论】:

  • 只是对此的后继怀疑 .. list4 = ''.join(c for c in list3) print(list4 is list3) .. 那么为什么这会给出 False 作为输出,因为这也会创建相同的字符串
  • 严格来说,st 是否引用同一个字符串对象是一个实现细节。这与 OP 的问题有点不同,其中一个字符串是字符串操作的结果,而不是相同字符串文字的重复。
  • 我认为如果他们不引用同一个对象,则 id() 上没有匹配 OP 询问
  • 只是对此的后继怀疑 .. list4 = ''.join(c for c in list3) print(list4 is list3) .. 那么为什么这会给出 False 作为输出,因为这也会创建相同的字符串@BingWang
  • @Kumar 你是对的。对不起,从来没有意识到这一点
猜你喜欢
  • 2018-07-25
  • 2012-07-21
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
  • 2019-11-25
相关资源
最近更新 更多