文章目录
1.字典
1.1字典的创建
字典的键值对是无序可变序列,键是不能重复的,值可以重复。 典型的字典定义方式:a = {'name':'gaoqi','age':18,'job':'programer'}
b = dict(name = 'gaiqi',age = 18, job = 'programmer')
a = dict([('name','gaiqi'),('age',18)])
c = {} #空的字典对象
d = dict() #空的字典对象
通过zip()创建字典对象
k = [‘name’,‘age’,‘job’]
v = [‘gaoqi’,18,‘teacher’]
d = dict(zip(k,v)) #d = {‘name’:‘gaoqi’,‘age’:18,‘job’:‘teacher’}
1.2字典的访问
1.通过【键】获得“值”。若键不存在,则抛出异常。
a[‘name’]
1.通过get()获得“值”。若键不存在,则返回none。
a.get(“dfaf”,“不存在”) #键不存在则返回"不存在"
a.items() #列出所有的键值对
a.keys() #列出所有的键
a.values() #列出所有的值
len(a) #一共有多少个键值对
“name” in a #“name”键是否在a字典中
1.3字典元素的添加、修改、删除
1.字典新增键值对,如果“键”存在则覆盖旧的“键”,如果不存在则增加新的“键”
b = dict(name = ‘gaiqi’,age = 18, job = ‘programmer’)
b[‘address’] = ‘红旗大街’
b[‘age’] = 16
2.使用update(),将新字典所有键值对加到旧字典上,键重复则覆盖
a.update(b)
3.删除
del(a[‘name’])
b = a.pop(‘age’) #a字典中age的值给pop,并删除a中的键值对
a.clear() #清空字典
a.popitem() #一次弹出键值对
1.4序列解包
a,b,c = s #对键解包
a,b,c = s.values() #对值解包
a,b,c = s.items() #对键值对解包
r1 = {"name":"高小一","age":18,"salary":30000,"city":"北京"}
r2 = {"name":"高小二","age":19,"salary":40000,"city":"上海"}
r3 = {"name":"高小一","age":20,"salary":50000,"city":"深圳"}
tb = [r1,r2,r3]
#获得第二行的人的薪资
print(tb[1].get("salary"))
#打印表中所有的薪资
for i in range(len(tb)):
print(tb[i].get("salary"))
#打印表中的所有的数据
for i in range(len(tb)):
print(tb[i].get("name"),tb[i].get("age"),tb[i].get("salary"),tb[i].get("city"))
1.5字典核心底层原理
字典对象的核心是散列表,散列表是一个稀疏数组,每个单元叫做bucket。bucket结构和大小一致,通过偏移量来读取制定的bucket。
字典需要先遍历在修改。
2.集合
集合是无序可变的,元素不能重复,底层逻辑是字典实现,字典中的键对象,是不可重复的唯一的。
a = {10,20,30,100}
a.remove()
a.clear()
b = {“he”,“it”,20}
a|b #并集
a&b #交集
a-b #差集
a.union(b) #并集
a.intersection(b) #交集
a.difference(b) #差集
3.控制语句
控制语句是代码的组合方式。
3.1单分支选择语句
通过缩进控制结构。
条件表达式中不能有赋值操作符“=”,如:不能出现if(a=true)
3.2双分支结构
if else
1.三元运算符
s = input("请输入一个数字")
#测试三元运算符
print("s是小于10的数字" if int(s)<10 else "s是大于等于10的数字")
2.多分支结构
if
elif
多分支机构,几个分支之间是有逻辑关系的,不能随意颠倒顺序。
#测试多分支选择结构
score = int(input("请输入分数:"))
grade = ""
if score<60:
grade = "不及格"
elif score<80:
grade = "及格"
elif score < 90:
grade = "良好"
else:
grade = "优秀"
print("分数是{0},等级是{1}".format(score,grade))
3.3选择结构的嵌套
#测试选择结构的嵌套
score = int(input("请输入一个在0-100之间的数字:"))
grade = ""
if score>100 or score<0:
score = int(input("输入错误!请重新输入一个0-100之间的数字"))
else:
if score>=90:
grade = "A"
elif score>=80:
grade = "B"
elif score >= 70:
grade = "C"
elif score>=60:
grade = "D"
else:
grade = "E"
print("分数是{0},等级是{1}".format(score,grade))
或者
# 测试选择结构的嵌套
score = int(input("请输入一个在0-100之间的数字:"))
degree = "ABCDE"
num = 0
if score > 100 or score < 0:
score = int(input("输入错误!请重新输入一个0-100之间的数字"))
else:
num = score // 10
if num < 6:
num = 5
print("分数是{0},等级是{1}".format(score, degree[9 - num]))
3.4循环结构
1.while循环
num = 0
while num <= 10:
print(num,end="\t")
num += 1
计算1-100累加和
#计算1-100之间的数字累加
num2 = 0
sumall = 0
while num2<=100:
sumall = sumall +num2
num2 +=1
print("1-100所有书的累加和",sumall)