Skip to main content
 首页 » 编程设计

python之在 python 中使用 id() 比较列表(整数)

2025年05月04日8webabcd

当我试图比较由整数组成的列表时,我在 Python 中发现了一件奇怪的事情。

例如:

In [35]: id(range(1,5)),id(range(1,15)),id(range(16,0,-1)) 
Out[35]: (155687404, 155687404, 155687404) 

Q1: 为什么它们的 id() 值相同?它们看起来不同,怎么可能相同?

Q2: 如何按 id() 值比较整数列表?

Q3: 更想知道的是,id() 值在 Python 中是如何计算的?

请您参考如下方法:

直接来自 python 的文档:

Return the “identity” of an object. This is an integer (or long integer)  
which is guaranteed to be unique and constant for this object during its lifetime.  
Two objects with non-overlapping lifetimes may have the same id() value. 

您可以获得 md5 哈希来比较这些对象:

import md5 
>>> md5.new(str(range(1,5))).hexdigest() 
'd5397571a7f9c05bd58bed77f9dbe8f0' 
>>> md5.new(str(range(1,15))).hexdigest() 
'000b3ca7f2653a13cdb5b96f21c2ba4d'