简单介绍:dict和set是有别于list和tuple类型的,list可以理解为python的动态数组,tuple可以理解为python的值不变的动态数组。
dict类似于c++的map,存储的单个元素的形式为<key, value>,根据key找到value,类似于查字典,查鲫、鲤、鳙等字,先查鱼字旁,鱼字旁就相当于key,后面的鲤等字就属于value
set的话是一个无序无重复元素的集合,比如{1,2,2,3,4,4,2,1},对于set的话,set里面实际存储为{1,2,3,4}
源代码:
#今天学习dict 和set 两种类型,注意dict是{},list和tuple是【】 d = {'linglaoda':1, 'zhulaoer':2, 'zhanglaosan':3} print(d) print(d['linglaoda']) print(d['zhulaoer']) print(d['zhanglaosan']) #常用的四种操作,增删改查 d['linglaoda'] = 4 print(d) d['lilaosi'] = 5 print(d) d.pop('linglaoda') print(d) i = d.get('zhanglaosan') print(i) #接下来看下set的操作,set理解为一个没有重复元素的无序集合 s = set([1,2,3]) print(s) s= set([1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,]) print(s) s.add(5) print(s) s.remove(1) print(s) s1 = ([2,3]) s2 = s&s1 print(s2) s3 = s|s1 print(s3) s = s&s2 print(s)源代码结果:
D:\python_prj\venv\Scripts\python.exe D:/python_prj/python9.py
Traceback (most recent call last):
{'linglaoda': 1, 'zhulaoer': 2, 'zhanglaosan': 3}
File "D:/python_prj/python9.py", line 33, in <module>
1
s2 = s&s1
2
TypeError: unsupported operand type(s) for &: 'set' and 'list'
3
{'linglaoda': 4, 'zhulaoer': 2, 'zhanglaosan': 3}
{'linglaoda': 4, 'zhulaoer': 2, 'zhanglaosan': 3, 'lilaosi': 5}
{'zhulaoer': 2, 'zhanglaosan': 3, 'lilaosi': 5}
3
{1, 2, 3}
{1, 2, 3}
{1, 2, 3, 5}
{2, 3, 5}
Process finished with exit code 1