python 数据结构 set
创建set tuple算是list和str的杂合,那么set则可以堪称是list和dict的杂合. set拥有类似dict的特点:可以用{}花括号来定义;其中的元素没有序列,也就是是非序列类型的数据;而且,set中的元素不可重复,这就类似dict的键. set也有继承了一点list的特点:如可以原处修改(事实上是一种类别的set可以原处修改,另外一种不可以). 实验: >>> s1 = set("hiekaye") #把str中的字符拆解开,形成set.特别注意观察:hiekay3中有两个e >>> s1 #但是在s1中,只有一个i,也就是不能重复 set(['h', 'i', '3', 'k', 'a','y']) >>> s2 = set([123,"google","face","book","facebook","book"]) #通过list创建set.不能有重复,元素可以是int/str >>> s2 set(['facebook', 123, 'google', 'book', 'face']) #元素顺序排列不是按照指定顺序 >>> s3 = {"facebook",123} #通过{}直接创建 >>> s3 set([123, 'facebook']) 探究: >>> s3 = {"facebook",[1,2,'a'],{"name":"python","lang":"english"},123} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict' >>> s3 = {"facebook",[1,2],123} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' 从上述实验中,可以看出,通过{}无法创建含有list/dict元素的set. 继续探索: >>> s1 set(['q', 'i', 's', 'r', 'w']) >>> s1[1] = "I" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'set' object does not support item assignment >>> s1 set(['q', 'i', 's', 'r', 'w']) >>> lst = list(s1) >>> lst ['q', 'i', 's', 'r', 'w'] >>> lst[1] = "I" >>> lst ['q', 'I', 's', 'r', 'w'] 上面的探索中,将set和list做了一个对比,虽然说两者都能够做原处修改,但是,通过索引编号(偏移量)的方式,直接修改,list允许,但是set报错. 那么,set如何修改呢? 更改set 把set的有关内置函数找出来. >>> dir(set) ['__and__', '__class__', '__cmp__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update'] 先看这些: 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update' 然后用help()可以找到每个函数的具体使用方法,下面列几个例子: 增加元素 >>> help(set.add) Help on method_descriptor: add(...) Add an element to a set. This has no effect if the element is already present. 实验: >>> a_set = {} #我想当然地认为这样也可以建立一个set >>> a_set.add("hiekay") #报错.看看错误信息,居然告诉我dict没有add.我分明建立的是set呀. Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'dict' object has no attribute 'add' >>> type(a_set) #type之后发现,计算机认为我建立的是一个dict <type 'dict'> 特别说明一下,{}这个东西,在dict和set中都用.但是,如上面的方法建立的是dict,不是set.这是python规定的.要建立set,只能用前面介绍的方法了. >>> a_set = {'a','i'} #这回就是set了吧 >>> type(a_set) <type 'set'> #果然 >>> a_set.add("hiekay") #增加一个元素 >>> a_set #原处修改,即原来的a_set引用对象已经改变 set(['i', 'a', 'hiekay']) >>> b_set = set("python") >>> type(b_set) <type 'set'> >>> b_set set(['h', 'o', 'n', 'p', 't', 'y']) >>> b_set.add("hiekay") >>> b_set set(['h', 'o', 'n', 'p', 't', 'hiekay', 'y']) >>> b_set.add([1,2,3]) #这样做是不行滴,跟前面一样,报错. Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' >>> b_set.add('[1,2,3]') #可以这样! >>> b_set set(['[1,2,3]', 'h', 'o', 'n', 'p', 't', 'hiekay', 'y']) 从另外一个set中合并过来元素,方法是set.update(s2) >>> help(set.update) update(...) Update a set with the union of itself and others. >>> s1 set(['a', 'b']) >>> s2 set(['github', 'hiekay']) >>> s1.update(s2) #把s2的元素并入到s1中. >>> s1 #s1的引用对象修改 set(['a', 'hiekay', 'b', 'github']) >>> s2 #s2的未变 set(['github', 'hiekay']) 删除 >>> help(set.pop) pop(...) Remove and return an arbitrary set element. Raises KeyError if the set is empty. >>> b_set set(['[1,2,3]', 'h', 'o', 'n', 'p', 't', 'hiekay', 'y']) >>> b_set.pop() #从set中任意选一个删除,并返回该值 '[1,2,3]' >>> b_set.pop() 'h' >>> b_set.pop() 'o' >>> b_set set(['n', 'p', 't', 'hiekay', 'y']) >>> b_set.pop("n") #如果要指定删除某个元素,报错了. Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: pop() takes no arguments (1 given) set.pop()是从set中任意选一个元素,删除并将这个值返回.但是,不能指定删除某个元素.报错信息中就告诉我们了,pop()不能有参数.此外,如果set是空的了,也报错.这条是帮助信息告诉我们的. 要删除指定的元素,怎么办? >>> help(set.remove) remove(...) Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. set.remove(obj)中的obj,必须是set中的元素,否则就报错.试一试: >>> a_set set(['i', 'a', 'hiekay']) >>> a_set.remove("i") >>> a_set set(['a', 'hiekay']) >>> a_set.remove("w") Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'w' discard(obj): >>> help(set.discard) discard(...) Remove an element from a set if it is a member. If the element is not a member, do nothing. 与help(set.remove)的信息对比,看看有什么不同.discard(obj)中的obj如果是set中的元素,就删除,如果不是,就什么也不做,do nothing. >>> a_set.discard('a') >>> a_set set(['hiekay']) >>> a_set.discard('b') >>> set.clear(),它的功能是:Remove all elements from this set. >>> a_set set(['hiekay']) >>> a_set.clear() >>> a_set set([]) >>> bool(a_set) #空了,bool一下返回False. False