现在的位置: 首页 > 综合 > 正文

python中set集合如何决定是否重复? python中set集合如何决定是否重复?

2017年11月04日 ⁄ 综合 ⁄ 共 1162字 ⁄ 字号 评论关闭
 

python中set集合如何决定是否重复?

分类: python 96人阅读 评论(0) 收藏 举报

http://heipark.iteye.com/blog/1743819

看下面代码,两个值相同的Item对象,添加到set中被认为是两个对象。

[python] view
plain
copy

  1. class Item(object):  
  2.   
  3.     def __init__(self, foo, bar):  
  4.         self.foo = foo  
  5.         self.bar = bar  
  6.       
  7.     def __repr__(self):  
  8.         return "Item(%s, %s)" % (self.foo, self.bar)  
  9.       
  10. print set([Item('1''2'), Item('1''2')])  
  11.   
  12. # 输出: set([Item(1, 2), Item(1, 2)])  

数据结构中HASH表的设计思路是:

  1. 被插入元素根据hash值决定插入那个桶(通常一个数组)中
  2. 新插入元素根据的equals方法依次比较桶内元素,以确定是否已经存在

 

在python中如果我们自定义class,则需要添加__hash____eq__两个方法,前者用于决定当前元素在哪个桶,后者决定当前元素是否在桶中已经存在。

 

修改后的code如下:

[python] view
plain
copy

  1. class Item(object):  
  2.     def __init__(self, foo, bar):  
  3.         self.foo = foo  
  4.         self.bar = bar  
  5.       
  6.     def __repr__(self):  
  7.         return "Item(%s, %s)" % (self.foo, self.bar)  
  8.       
  9.     def __eq__(self, other):  
  10.         if isinstance(other, Item):  
  11.             return ((self.foo == other.foo) and (self.bar == other.bar))  
  12.         else:  
  13.             return False  
  14.       
  15.     def __hash__(self):  
  16.         return hash(self.foo + " " + self.bar)  
  17.   
  18. print set([Item('1''2'), Item('1''2')])  
  19.   
  20. # 输出:set([Item(1, 2)])  

抱歉!评论已关闭.