python set
来源:互联网 发布:携程php招聘 编辑:程序博客网 时间:2024/06/06 04:28
一、定义
set是一个无序且不重复的元素集合。
集合对象是一组无序排列的可哈希的值,集合成员可以做字典中的键。集合支持用in和not in操作符检查成员,由len()内建函数得到集合的基数(大小), 用 for 循环迭代集合的成员。但是因为集合本身是无序的,不可以为集合创建索引或执行切片(slice)操作,也没有键(keys)可用来获取集合中元素的值。
set和dict一样,只是没有value,相当于dict的key集合,由于dict的key是不重复的,且key是不可变对象因此set也有如下特性:
不重复
元素为不可变对象
二、创建
s = set()
s = {11,22,33,44} #注意在创建空集合的时候只能使用s=set(),因为s={}创建的是空字典
a=set('boy')b=set(['y', 'b', 'o','o'])c=set({"k1":'v1','k2':'v2'})d={'k1','k2','k2'}e={('k1', 'k2','k2')}print(a,type(a))print(b,type(b))print(c,type(c))print(d,type(d))print(e,type(e))OUTPUT:{'o', 'b', 'y'} <class 'set'>{'o', 'b', 'y'} <class 'set'>{'k1', 'k2'} <class 'set'>{'k1', 'k2'} <class 'set'>{('k1', 'k2', 'k2')} <class 'set'>
三、基本操作
比较
se = {11, 22, 33}be = {22, 55}temp1 = se.difference(be) #找到se中存在,be中不存在的集合,返回新值print(temp1) #{33, 11}print(se) #{33, 11, 22}temp2 = se.difference_update(be) #找到se中存在,be中不存在的集合,覆盖掉seprint(temp2) #Noneprint(se) #{33, 11},
删除
discard()、remove()、pop()
se = {11, 22, 33}se.discard(11)se.discard(44) # 移除不存的元素不会报错print(se)se = {11, 22, 33}se.remove(11)se.remove(44) # 移除不存的元素会报错print(se)se = {11, 22, 33} # 移除末尾元素并把移除的元素赋给新值temp = se.pop()print(temp) # 33print(se) # {11, 22}
取交集
intersection()
se = {11, 22, 33}be = {22, 55}temp1 = se.intersection(be) #取交集,赋给新值print(temp1) # 22print(se) # {11, 22, 33}temp2 = se.intersection_update(be) #取交集并更新自己print(temp2) # Noneprint(se) # 22
判断
isdisjoint issebset issuperset
se = {11, 22, 33}be = {22}print(se.isdisjoint(be)) #False,没有相同项 返回trueprint(se.issubset(be)) #False,判断se是否是be的子集合print(se.issuperset(be)) #True, 判断se是否是be的父集合
合并
symmetric_difference_update
se = {11, 22, 33}be = {22}temp1 = se.symmetric_difference(be) # 合并不同项,并赋新值print(temp1) #{33, 11}print(se) #{33, 11, 22}temp2 = se.symmetric_difference_update(be) # 合并不同项,并更新自己print(temp2) #Noneprint(se) #{33, 11}
取并集
union()
se = {11, 22, 33}be = {22,44,55}temp=se.union(be) #取并集,并赋新值print(se) #{33, 11, 22}print(temp) #{33, 22, 55, 11, 44}
更新
update()
se = {11, 22, 33}be = {22,44,55}se.update(be) # 把se和be合并,得出的值覆盖seprint(se)se.update([66, 77]) # 可增加迭代项print(se)
集合的转换
se = set(range(4))li = list(se)tu = tuple(se)st = str(se)print(li,type(li))print(tu,type(tu))print(st,type(st))OUTPUT:[0, 1, 2, 3] <class 'list'>(0, 1, 2, 3) <class 'tuple'>{0, 1, 2, 3} <class 'str'>
阅读全文
0 0
- Python Set
- python set
- python set
- python--set
- python set
- python set
- python set
- Python---set
- Python set
- python set
- python set
- python set
- python-set
- Python set
- python set()
- python set
- Python Set
- python ---- set
- C++容易忘记的知识点——map和set(六)
- 树链剖分 模板 洛谷p3384
- git基础操作
- 移动端兼容性问题总结0
- php-fpm安装、配置与优化
- python set
- service的基本运用
- PL/SQL
- linux 鸟哥私房菜笔记篇
- Rxjava2-小白快速入门
- LeetCode算法问题7 —— Longest Substring Without Repeating Characters
- Struts2简介
- C++ MFC / VS2013 之十四 (对话框:消息对话框)
- Normalization(标准化)的原理和实现详解