python--集合概念和实战(一)
有的可变,有的不可变;元素无次序,不可重复。
创建集合(set)说明⚠️:
元组算是列表和字符串的某些特征的杂合,那么集合则可以算是列表和字典的某些特征杂合。
使用set创建集合>>> s = set("wtf")>>> sset(['t', 'w', 'f'])把字符串中的字符拆解开,形成集合。>>> s1 = set("zhaodidi")>>> s1set(['a', 'd', 'i', 'h', 'o', 'z'])”haodidi“中有两个“d”和“i”,创建集合时,如发现重复元素,就会过滤掉。
使用 {} 创建集合
>>> s2 = {"python",123}>>> s2set(['python', 123])
说明⚠️:
这种方法不提倡,因为 {} 常常被用于字典上,应避免歧义!特别说明,建立空集合时一定要使用 set() ,不要使用 {} !否则建立的就是字典而非集合。下面是实例说明为什么创建集合不提倡使用 {}
>>> s3 = {"datagrand",[1,2,'b'],{"name":"python","lang":"chinese"},123}Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unhashable type: 'dict'>>> s4 = set("'datagrand',[1,2,'b'],{'name':'python','lang':'chinese'},123")>>> s4set(["'", ',', '1', '3', '2', ':', '[', ']', 'a', 'c', 'b', 'e', 'd', 'g', 'i', 'h', 'm', 'l', 'o', 'n', 'p', 's', 'r', 't', 'y', '{', '}'])
说明⚠️:使用 set() 建立起来的集合是可变集合,可变集合都是unhashable type。但是集合中的元素是 hashable type !
什么是 hashable(可哈希)和 unhashable(不可哈希)?简单理解就是,某数据unhashable(不可哈希)就是其可变,如list或dict。否则,就是hashable(可哈希),如字符串。
集合没有索引(index)>>> 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']上面列出的并没有“index”
>>> s1set(['a', 'd', 'i', 'h', 'o', 'z'])>>> s1[2]Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'set' object does not support indexing报错中明确告知,集合不支持索引!
集合(set)方法add (增加的是元素)
>>> help(set.add)Help on method_descriptor:add(...) Add an element to a set. This has no effect if the element is already present.(END)
实例说明如下:
>>> set1 = set()>>> set1set([])>>> set1.add("zhaodi") #属于原地修改>>> set1set(['zhaodi'])
>>> set2 = set("python")>>> set2set(['h', 'o', 'n', 'p', 't', 'y'])>>> set2.add("learning")>>> set2set(['h', 'o', 'n', 'p', 't', 'learning', 'y'])
这里重申下:“集合中的元素应该是 hashable 类型”
set2set(['h', 'o', 'n', 'p', 't', 'learning', 'y'])>>> set2.add([1,2,3])Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unhashable type: 'list'如果将列表 [1,2,3] 变成 hashable 类型呢?>>> set2.add('[1,2,3]') # 这里的 '[1,2,3]' 就相当于字符串了>>> set2set(['[1,2,3]', 'h', 'o', 'n', 'p', 't', 'learning', 'y'])
update(合并集合)
>>> help(set.update)Help on method_descriptor:update(...) Update a set with the union of itself and others. # 这个方法的作用是用原有的集合自身和其他的什么东西构成的新集合更新原来的集合。(END)
others是指作为参数的不可变对象,将它和原来的集合组成新的集合,用这个新集合替代原来的集合,如下:
>>> set1set(['zhaodi'])>>> set1.update("wutf")>>> set1set(['f', 'u', 'zhaodi', 'w', 't'])>>> set1.update((3,4))>>> set1set([3, 4, 'f', 'u', 't', 'w', 'zhaodi'])
合并集合,举例如下:
>>> set1set(['zhaodi'])>>> set2set(['[1,2,3]', 'h', 'o', 'n', 'p', 't', 'learning', 'y'])>>> set2.update(set1) # 把 set1 的元素并入到 set2 中>>> set2set(['[1,2,3]', 'h', 'o', 'n', 'p', 't', 'learning', 'y', 'zhaodi'])>>> set1 # set1 并没有改变set(['zhaodi'])
pop(删除集合中任意元素)
>>> help(set.pop)Help on method_descriptor:pop(...) Remove and return an arbitrary(随意) set element. Raises KeyError if the set is empty.(END)
pop 删除任意一个集合元素
>>> set1set([3, 4, 'f', 'u', 't', 'w', 'zhaodi'])>>> set1.pop()3>>> set1.pop()4>>> set1.pop()'f'>>> set1set(['u', 't', 'w', 'zhaodi'])
pop 删除指定元素 (不能的)
>>> set1set(['u', 't', 'w', 'zhaodi'])>>> set1.pop('zhaodi')Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: pop() takes no arguments (1 given) # pop() 不能有参数的
说明⚠️:
set.pop() 是从set中任意选一个元素,删除并将这个值返回pop() 不能有参数,所以 pop 不能指定删除集合中某个元素如果集合已经为空,再删除,也报错remove(删除集合中指定元素,有报错信息)>>> help(set.remove)Help on method_descriptor:remove(...) Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError.(END)
说明⚠️:set.remove(obj) 中的 obj 必须是 set 中的元素,否则就报错。实例如下:
>>> set1set(['u', 't', 'w', 'zhaodi'])>>> set1.remove("wtf") # 没有 “wtf” 这个元素Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: 'wtf'>>> set1.remove("w")>>> set1set(['u', 't', 'zhaodi'])
discard(删除集合中指定元素,无报错信息)
>>> help(set.discard)Help on method_descriptor:discard(...) Remove an element from a set if it is a member. If the element is not a member, do nothing.(END)
说明⚠️:
与 set.remove 功能相似discard(obj) 中的 obj 如果是集合中的元素,就删除;如果不是,就什么都不做(do nothing)>>> set1set(['u', 't', 'zhaodi'])>>> set1.discard("u")>>> set1.discard("wtf")>>> set1set(['t', 'zhaodi'])
clear (删除集合中的所有元素)
>>> help(set.clear)Help on method_descriptor:clear(...) Remove all elements from this set.(END)
实例如下:
>>> set1set(['t', 'zhaodi'])>>> set1.clear()>>> set1set([])
写在最后的话
这篇博文是参考老齐老师的大作《跟老齐学python》进行简单总结的,这里没有打广告的意思,只是感觉老齐老师的书很适合python小白学习,内容读起来很轻快,老齐老师的书籍逻辑很清晰,有需要的朋友可以看看~~
gitbook版本:《跟老齐学Python》(入门教程)
我当时买时书籍样纸如下:
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。