python 数据结构

一.Python 集合set()添加删除、交集、并集、集合操作详解

Python set基本数据类型的一种集合类型,它有可变集合(set())和不可变集合(frozenset)两种。创建集合set集合set添加集合删除交集并集差集的操作都是非常实用的方法。

1.python set类是在python的sets模块中,大家现在使用的python2.7.x中,不需要导入sets模块可以直接创建集合。
>>>set('boy')
set(['y', 'b', 'o'])

set()的值不能重复

2.集合添加、删除

python 集合的添加有两种常用方法,分别是add和update。
集合add方法:是把要传入的元素做为一个整个添加到集合中,例如:
>>> a = set('boy')
>>> a.add('python')
>>> a
set(['y', 'python', 'b', 'o'])

3.集合update方法:是把要传入的元素拆分,做为个体传入到集合中,例如:
>>> a = set('boy')
>>> a.update('python')
>>> a
set(['b', 'h', 'o', 'n', 'p', 't', 'y'])

4.集合删除操作方法:remove
set(['y', 'python', 'b', 'o'])
>>> a.remove('python')
>>> a
set(['y', 'b', 'o'])

5.python set() 集合操作符号、数学符号

集合的交集、合集(并集)、差集,了解python集合set与列表list的这些非常好用的功能前,要先了解一些集合操作符号

python 数据结构

可变集合python set是www.iplaypy.com玩蛇网python学习交流平台,初期python学习中比较能接触到的。像列表字典字符串这类可迭代的对像都可以做为集合的参数。set集合是无序的,不能通过索引和切片来做一些操作。

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

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

  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如下: 

    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)])