繁体   English   中英

如何在Python集合中获取对对象的引用

[英]How to get a reference to an object in Python set

假设我有一个包含对象的集合。

class C(object):
    def __init__(self, value):
        self.value = value
    def __repr__(self):
        return 'C({}):{}'.format(self.value, id(self))
    def __eq__(self, other):
        return self.value == other.value
    def __hash__(self):
        return hash(self.value)

cset = {C(1), C(2)}
print 'cset:', cset

cset: set([C(1):140241436167120, C(2):140241436167184])

我想在集合中找到一个对象,并获取对该对象的引用。

c1 = C(1)
print 'c1:', c1

found, = cset & {c1}
print 'way1 found:', found
found, = {c1} & cset
print 'way2 found:', found

c1: C(1):140241436167248
way1 found: C(1):140241436167248
way2 found: C(1):140241436167248

那些方法不好。 返回对c1(id = 140241436167248)的引用,而不是对集合中的对象(id = 140241436167120)的引用。

只是为了显示我想要的,快速而肮脏的方式就是这样。

found, = [x for x in cset if x == c1]
print 'way3 found:', found

way3 found: C(1):140241436167120

这种方式返回我想要的,即对集中对象(id = 140241436167120)的引用。 但是它正在使用线性搜索。 有什么更好的办法吗?

问题是您试图像映射一样使用set 效果不好...

相反,不要使您的对象明确地可哈希化。 如果您具有唯一性约束,请使用字典将值映射到实例而不是集合。 字典可以像set一样容易地执行唯一性,并且字典可以提供所需的映射行为。

if c1.value in cdict:
    c1 = cdict[c1.value]  # Trade in the `c1` we have for one already in `cdict`

另外,使用dict不太“聪明”,从可读性的角度来看,这几乎总是胜利。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM