#集合创建
a =set()print(type(a))
#集合元素不可重复
a ={1,2,2,3,3,3,4,100,99}print(a)#输出的为不重复元素,且也是无序的元素
#成员检测
a ={1,2,2,3,'music'}if'music'in a:print('你猜对了')
#元素遍历for i in a:print(i)#类型转化 tuple change to set
a =(12,'music','program','code',1,2,2)
b =set(a)print(b)#结果:<class'set'>{1,2,3,100,4,99}
你猜对了
123
music
{'program',1,2,'code',12,'music'}
集合的生成式
#集合的生成式
a ={1,2,3,4,5,6,7,8,9,10}
b ={i for i in a if i %2==0}#{ } 内部使用for循环和if语句进行新的集合的生成print(b)#结果:{2,4,6,8,10}
集合中的内置函数
add 添加元素
clear 清空集合
remove/discard 删除指定元素
#add添加元素
a ={10,20,30,40,50}
a.add(60)print(a)#注意不可直接打印print(a.add(60))
#clea清空元素
a.clear()print(a)
```python
#remove删除指定元素
a ={1,2,3,4,5}
a.remove(1)print(a)#注意:discard也为删除指定元素(与remove区别在于remove删除原本不存在的元素时会报错,然而discard不会)
#结果:{40,10,50,20,60,30}set(){2,3,4,5}
#union并集
a ={1,2,3}
b ={2,3,6}print(a.union(b))
#intersection交集print(a.intersection(b))
#difference差集
a ={1,2,3}
b ={2,3,6}print(a.difference(b))#结果:{1,2,3,6}{2,3}{1}
字典 - dict
字典是一种组合数据,没有顺序的组合数据,以键值对(key-value)的方式实现
#创建字典#方法1
d ={}print(type(d))#方法2
d =dict()print(type(d))#方法3
d ={'name':'xiaobai','age':18,'height':180}#常用方法print(type(d))print(d)#方法4利用字典
d =dict({'name':'xiaobai','age':18,'height':170})print(d)#方法5利用关键字参数
d =dict(name='xiaobai',age=18,height=160)print(d)#利用利用元组
d =dict([('name','xiaobai'),('age',18),('height',150)])print(d)#结果:<class'dict'><class'dict'><class'dict'>{'name':'xiaobai','age':18,'height':180}{'name':'xiaobai','age':18,'height':170}{'name':'xiaobai','age':18,'height':160}{'name':'xiaobai','age':18,'height':150}
#字典的访问
d ={'one':1,'tow':2,'three':3}print(d['one'])
#字典的删除del d['one']print(d)
#结果:1{'tow':2,'three':3}
#成员检测#检测的是键而不是值
d ={'one':1,'tow':2,'three':3}
if'one'in d:print('哈哈')if1in d:#检测的是键而不是值print('哈哈')
#结果:
哈哈
#字典的遍历
d ={'one':5,'tow':6,'three':7}for a in d:print(a, d[a])print('*'*10)#访问所有键:for i in d.keys():print(i)print('*'*10)#访问所有值:for i in d.values():print(i)#结果:
one 5
tow 6
three 7**********
one
tow
three
**********567
#特殊操作items()#返回可遍历的(键, 值) ,以元组形式输出
d ={'one':5,'tow':6,'three':7}
for a,b in d.items():print(a,b)#结果:
one 5
tow 6
three 7
字典生成式
常规操作 {for…}
加限制条件操作 {for… if…}
#字典生成式(常规操作)
d ={'one':1,'two':2,'three':3}
dd ={a:b for a,b in d.items()}print(dd)print('*'*10)
#字典生成式(加限制条件操作)print({a:b for a,b in d.items()if b %2==0})#结果:{'one':1,'two':2,'three':3}{'one':1,'two':2,'three':3}**********{'two':2}
d ={'b':4,'c':5,'d':12,'e':10}#len()print(len(d))#max()print(max(d))#max(dict,key = dic.get)print(max(d,key = d.get))#str()print(str(d))#keys()print(d.keys())#clean()print(d.clear())print(d)4
e
d
{'b':4,'c':5,'d':12,'e':10}
dict_keys(['b','c','d','e'])None{}#get()用法
d ={'one':1,'two':2,'three':3}print(d.get('one'))print(d.get('four',4))print(d)#结果:14{'one':1,'two':2,'three':3}#fromkeys()案例
d =dict.fromkeys(range(5),'happy')print(d)
c =dict.fromkeys(['one','two'],'TO')print(c){0:'happy',1:'happy',2:'happy',3:'happy',4:'happy'}{'one':'TO','two':'TO'}