Python个人学习记录(2) 字典/元组/集合/字符串

202 阅读2分钟

字典

什么是字典

image.png

lst={"小明":10,"小红":20,"小王":30}   #键与值
print(lst)
print(type(lst))


结果:
{'小明': 10, '小红': 20, '小王': 30}
<class 'dict'>

字典原理

哈希函数计算 image.png

字典创建与删除

image.png

"""使用花括号创建字典"""
lst={"小明":10,"小红":20,"小王":30}
print(lst)
print(type(lst))



"""自带函数dict创建字典"""
su1=dict(name="20",age=20)     #前面是键,后面是值
print(su1)
print(type(su1))


"""空字典"""
d={}
print(d)


结果:
{'小明': 10, '小红': 20, '小王': 30}
<class 'dict'>
{'name': '20', 'age': 20}
<class 'dict'>
{}

字典查询

image.png

lst={"1":10,"2":20,"3":30}


"""使用[]"""       #[]与get的区别在于,[]如果没有这个键,会报错,get会显示none
print(lst["2"])


"""使用get方法"""
print(lst.get("1"))
print(lst.get("5"))   #None
print(lst.get("5",99))   #995这个键不存在時,提供的默认值


结果:
20
10
None
99

字典增删改

image.png

判断:

lst={"1":10,"2":20,"3":30}


print("2" in lst)  #只判断键
print(30 in lst)
print(2 in lst)


True
False
False

删除:

lst={"1":10,"2":20,"3":30}

del lst["1"]     #键值一起删
print(lst)

lst.clear()      #清空
print(lst)


{'2': 20, '3': 30}
{}

修改:

lst={"1":10,"2":20,"3":30}
lst["4"]=80
lst["2"]=80   #无key新增,有key修改

print(lst)



{'1': 10, '2': 80, '3': 30, '4': 80}

获取视图:

image.png

lst={"1":10,"2":20,"3":30}

  
"""获取所有键"""
key=lst.keys()
print(key)

"""获取所有值"""
value=lst.values()
print(value)

"""获取键与值"""
item=lst.items()
print(item)



dict_keys(['1', '2', '3'])
dict_values([10, 20, 30])
dict_items([('1', 10), ('2', 20), ('3', 30)])

字典遍历

image.png

lst={"1":10,"2":20,"3":30}

for item in lst:
    print(item,lst[item],lst.get(item))
    
    
    
1 10 10
2 20 20
3 30 30    

image.png

字典生成式

image.png

image.png

items=["A","B","C"]
price=[70,80,50]

dic={ items:price  for items,price in zip(items,price)}
print(dic)


结果:
{'A': 70, 'B': 80, 'C': 50}

总结

image.png

元组

image.png

创建元组

image.png

"""第一种,小括号"""
ias=(1,2,3,4)
print(ias)

"""第二种,内置函数tuple"""
t=tuple((1,4,3,6))
print(t)

a1=(1)
a2=(1,)   #如果只有一个元素,必须逗号区分
print(type(a1),type(a2))



"""空元组"""
bb=tuple()
t1=()
print(bb,t1)


结果:
(1, 2, 3, 4)
(1, 4, 3, 6)
<class 'int'> <class 'tuple'>
() ()

遍历元组

image.png


t=(10,[20,30],9)
for item in t:
    print(item)

集合