1.字典
-
字典是一个无序的,key是唯一的,可变的集合 -
字典中的key是唯一的 1.1系统功能
dict1 = {"zhangsan":10,'lisi':18}
print(dict1['zhangsan'])
dict1['tom'] = 20
print(dict1)
dict2 = {'aaa':10,'bbb':15,'lisi':66}
dict1.update(dict2)
print(dict1)
print(dict2)
"""
如果default省略,向字典中添加一对键值对,为key:None
如果default不省略,向字典中添加一对键值对,为key:default【这个default 也就是你写的那个值】
"""
dict1 = {"zhangsan":10,'lisi':18}
print(dict1)
dict1.setdefault("hello")
print(dict1)
dict1.setdefault("abc",888)
print(dict1)
dict1 = {"zhangsan":10,'lisi':18}
print(dict1)
r1 = dict1.pop("lisi")
print(dict1)
print(r1)
dict2 = {"zhangsan":10,'lisi':18,'a':10,'b':20,'f':34}
print(dict2)
dict2.popitem()
print(dict2)
dict3 = {"zhangsan":10,'lisi':18,'a':10,'b':20,'f':34}
del dict3['a']
print(dict3)
dict3.clear()
print(dict3)
dict1 = {"zhangsan":10,'lisi':18}
print(dict1)
dict1['lisi'] = 100
print(dict1)
print(len(dict1))
dict2 = {"zhangsan":10,'lisi':18}
print(dict2['lisi'])
print(dict2.get("lisi"))
print(dict2.get('tom'))
print(dict2.get("lisi",'aaaa'))
print(dict2.get('tom','bbbb'))
dict1 = dict.fromkeys([11,22])
print(dict1)
dict1 = dict.fromkeys((11,22))
print(dict1)
dict1 = dict.fromkeys([11,22],"aaa")
print(dict1)
dict1 = dict.fromkeys((11,22),"aaa")
print(dict1)
dict1 = dict.fromkeys((11,22),('a','b'))
print(dict1)
dict1 = dict(zip([11,22],['a','b']))
print(dict1)
dict2 = dict.fromkeys([11,22],['a','b'])
print(dict2)
dict2 = {"name":"张三","age":19,"hobby":"篮球"}
dict3 = dict2
dict2['name'] = "jack"
print(dict2)
print(dict3)
dict2 = {"name":"张三","age":19,"hobby":"篮球"}
dict3 = dict2.copy()
dict2['name'] = "jack"
print(dict2)
print(dict3)
import copy
list1 = [1,2,3,{"name":"张三","age":19}]
list2 = copy.copy(list1)
list1[-1]['age'] = 66
print(list1)
print(list2)
import copy
list1 = [1,2,3,{"name":"张三","age":19}]
list2 = copy.deepcopy(list1)
list1[-1]['age'] = 66
print(list1)
print(list2)
1.2字典推导式
- 语法:{key:value for循环 if判断}
- 字典推导式又叫字典生成式 [注意:简单逻辑用这个推导式,但是逻辑复杂的话不要用推导式]
dict1 = {'aaa':10,"bbb":20}
d1 = {}
for key,value in dict1.items():
d1[value] = key
print(d1)
dict1 = {'aaa':10,"bbb":20}
d2 = {value:key for key,value in dict1.items()}
print(d2)
d3 = {i:i ** 2 for i in range(6)}
print(d3)
d3 = {i:i ** 2 for i in range(6) if i % 2 == 1}
print(d3)
list1 = [m + n for m in "xyz" for n in "abc"]
print(list1)
dict4 = {m:n for m in "xyz" for n in "abc"}
print(dict4)
1.3字典练兵
list1 = [11,22,33,44,55]
list2 = ['a','b','c','d','e']
dict11 = {}
for i in range(len(list1)):
dict11[list1[i]] = list2[i]
list1 = [11,22,33,44,55,66,77,88]
list2 = ['a','b','c','d','e']
dict11 = {}
if len(list1) > len(list2):
for i in range(len(list2)):
dict11[list1[i]] = list2[i]
else:
for i in range(len(list1)):
dict11[list1[i]] = list2[i]
list1 = [3,5,4,65,6,56,5,100,456,5,65]
sublist1 = []
sublist2 = []
for num in list1:
if num > 60:
sublist1.append(num)
else:
sublist2.append(num)
dict1 = {"k1":sublist1,"k2":sublist2}
"""
模拟商品购物车,实现向购物车中添加商品和删除商品的操作
要求:
a.模拟商品数据,包括商品名称,价格
b.引导用户选择需要操作的功能,如:添加,删除,退出
c.引导用户输入总资产
d.如果选择添加功能,则判断商品单价和总资产的关系,如果小于,则添加到购物车,默认添加数量为1个
e.如果选择删除功能,则引导用户输入需要删除的商品名称,从购物车中删除
"""
print("****欢迎****".center(60))
goods_list = [
{"name":"电脑","price":8888},
{"name":"book","price":78},
{"name":"phone","price":4000},
{"name":"自行车","price":2000}
]
total_money = int(input("请充值:"))
print("当前可供选择的商品如下:")
for i in range(len(goods_list)):
print("%d:%s"%(i,goods_list[i]))
shopcar_list = []
while True:
print("""当前购物系统中有如下功能:
0.添加商品
1.删除商品
2.结算购物车
3.退出
""")
choice = input("请输入需要进行的操作:")
if choice.isdigit() and choice in [str(i) for i in range(3+1)]:
if choice =="0":
index = input("请输入需要购买的商品编号[0-3]:")
if index.isdigit():
index = int(index)
if index in range(3+1):
goods_dict = goods_list[index]
if goods_dict['price'] <= total_money:
shopcar_list.append(goods_dict)
total_money -= goods_dict["price"]
print("添加商品成功!!!")
print(f"shopcar_list中商品有{shopcar_list}")
else:
print("余额不足")
else:
print("该商品不存在")
else:
print("输入的编号有误")
elif choice =="1":
goods_name = input("请输入需要删除的商品的名称:")
count =0
for subdict in shopcar_list:
if subdict["name"] == goods_name:
shopcar_list.remove(subdict)
total_money += subdict["price"]
print("删除成功")
break
else:
count+=1
if count==len(shopcar_list):
count = 0
print("你所想要删除的商品不存在")
elif choice =="2":
shopcar_money = 0
for subdic in shopcar_list:
shopcar_money += subdict["price"]
print("总共花费:%d¥,剩余%d¥"%
(shopcar_money,total_money))
shopcar_list.clear()
else:
print("欢迎再次光临".center(6,"*"))
break
else:
print("功能选择有误")
"""
要求:
a.模拟商品数据,包括商品名称,价格
b.引导用户选择需要操作的功能,如:添加,删除,退出
c.引导用户输入总资产
d.如果选择添加功能,则判断商品单价和总资产的关系,如果小于,则添加到购物车,默认添加数量为1个
e.如果选择删除功能,则引导用户输入需要删除的商品名称,从购物车中删除
"""
print("*************欢迎进入自助购物商店***********")
total_money = int(input("请充值:"))
def add_goods():
global total_money
index = input("请输入需要购买的商品编号【0~3】:")
if index.isdigit():
index = int(index)
if index in range(4):
goods_dict = goods_list[index]
if goods_dict['price'] <= total_money:
shopcar_list.append(goods_dict)
total_money -= goods_dict['price']
print("商品添加成功!")
else:
print("余额不足")
else:
print("该商品不存在")
else:
print("编号输入有误")
def del_goods():
global total_money
goods_name = input("请输入需要删除的商品的名称:")
for subdict in shopcar_list:
if subdict["name"] == goods_name:
shopcar_list.remove(subdict)
total_money += subdict["price"]
break
else:
print("你输入的商品不存在")
print("删除成功!")
def cal():
shopcar_money = 0
for subdict in shopcar_list:
shopcar_money += subdict["price"]
print("总共花费:%d¥,剩余%d¥" % (shopcar_money, total_money))
shopcar_list.clear()
goods_list = [
{"name":"电脑","price":8888},
{"name":"book","price":78},
{"name":"phone","price":4000},
{"name":"自行车","price":2000}
]
print("当前可供选择的商品如下:")
for i in range(len(goods_list)):
print("%d:%s" % (i,goods_list[i]))
shopcar_list = []
while True:
print("""当前购物系统中有如下功能:
0.添加商品
1.删除商品
2.结算购物车
3.退出""")
choice = input("请输入需要进行的操作:")
if choice.isdigit() and choice in [str(i) for i in range(4)]:
if choice == "0":
add_goods()
elif choice == '1':
del_goods()
elif choice == "2":
cal()
else:
print("欢迎再次光临")
break
else:
print("功能选择输入有误")
2.集合
-
Python中的集合跟数学上的集合是一致的,不允许有重复元素,而且可以进行交集、并集、差集等运算 -
set与dict类似,但是与dict的区别在于只是一组key的集合,不存储value -
集合的本质:是一种无序的,可变的,不允许存储重复元素的集合 -
表示:{},注意:如果直接使用{}则默认表示字典
set1 = {}
print(type(set1))
set2 = {3,4,6,7,8}
print(type(set2))
set31 = set()
print(set31)
set31 = set([])
print(set31)
set31 = set(())
print(set31)
set31 = set({})
print(set31)
set41 = {4,6,7,8,9}
set42 = set([4,6,7,8])
print(set42)
set42 = set((4,6,7,8))
print(set42)
set42 = set({"a":10,"b":20,"c":30})
print(set42)
set51 = {4,4,4,5,6,6}
print(set51)
set1 = {22,33,44,55,66}
print(set1)
set1.add(77)
print(set1)
set1.add("abc")
print(set1)
set1.add((2,3,4))
print(set1)
print(set1)
set1 = {22,33,44,55,66}
print(set1)
set1.update([77])
print(set1)
set1.update({"a":10,"b":20})
print(set1)
"""
【problem 】add和update之间的区别和联系
append和extend之间的区别和联系
相同点:
a.都是想集合中添加元素
b.都只能识别一个数据
不同点:
a.add只能添加不可变的数据类型
b.update只能添加可迭代对象【str,list,tuple,dict】
c.如果添加的数据为元组,add会将元组本身添加到集合中(整体加入),update只会将其中的元素添加到集合中(打碎加入)
"""
set1 = {22,33,44,55,66}
print(set1)
set1.remove(44)
print(set1)
set1 = {22,33,44,55,66}
print(set1)
set1.pop()
print(set1)
set1 = {22,33,44,55,66}
print(set1)
set1.discard(44)
print(set1)
set1.discard(100)
print(set1)
set1 = {22,33,44,55,66}
print(set1)
set1.clear()
print(set1)
print(len(set1))
print(max(set1))
print(min(set1))
set1 = {22,33,44,55,66}
print(set1)
set2 = set1.copy()
set1 = {1,2,3}
set2 = {3,4,5}
print(set1 & set2)
print(set1 | set2)
print(set1 - set2)
print(set1 ^ set2)
print(set1.intersection(set2))
print(set1.union(set2))
print(set1.difference(set2))
list1 = [34,65,65,65,6,6,6]
list2 = list(set(list1))
print(list2)
3.数字类型
"""
- abs(x):返回数字的绝对值
- (x>y)-(x<y):比较大小,
- max(x1,x2,…):返回给定参数的最大值
- min(x1,x2,…):返回给定参数的最小值
- pow(x,y):求x的y次方的值
- round(x,n):返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数
导入math模块 import math;
- ceil(x):返回x的上入整数,不能直接访问,需要通过math访问,即math.ceil(18.1)
- floor(x):返回x的下入整数,同ceil的用法
- modf(x):返回x的整数部分和小数部分,两部分的数值符号与x相同,整数部分以浮点型表示,同ceil的用法
- sqrt(x):返回数字x的平方根,返回类型为浮点型
数学常量
math.pi :圆周率
math.e :自然常数
"""
import math
print(abs(-19))
print(max([5,65,7,57,67]))
print(max(5,65,7,57,67))
print(min(5,65,7,57,67))
print(pow(5,3))
print(5 ** 3)
print(sum([1,2,3]))
print(sum((1,2,3)))
print(sum({1,2,3}))
print(sum({1,2,3},10))
print(round(8.23))
print(round(8.73))
print(round(8.23,1))
print(round(8.26,1))
print(round(8.233,2))
print(round(8.269,2))
print(sum(range(1,101)))
print(sum(range(0,101,2)))
print(math.ceil(16.9))
print(math.ceil(16.1))
print(math.floor(16.9))
print(math.floor(16.1))
print(math.sqrt(9))
print(math.pi)
print(math.e)
4.随机数
from random import *
print(choice([4,65,6]))
print(choice((4,65,6)))
print(choice(range(1,101)))
print(choice(range(0,101,2)))
print(choice(range(1,51)))
print(randint(1,50))
print(randrange(1,51))
print(choice(range(0,51,3)))
print(randrange(0,51,3))
print(random())
print(round(random(),2))
print(random() * 80 + 20)
"""
结论
求n~m(m > n)之间的随机数,包括整数和浮点数
则随机数的表示为:random() * (m - n) + n
"""
print(uniform(20,100))
5.字符串
-
字符串的本质:是一种有序的,不可变的,可以存储重复字符的集合 -
由若 干个字符组成的一个序列被称为字符串,其中的字符可以是字母,数字,符号,中文等 -
:字符串属于不可变的数据类型,可以作为字典的key
s1 = 'aa4中文%%¥'
print(s1)
s2 = "aa4中文%%¥"
print(s2)
s3 = """fahjg
56756
饿哦的
%¥¥##"""
print(s3)
"""
转义字符:在一个字符或者符号的前面添加\,则就可以将指定字符进行转义
普通字符----》特殊字符,如:n---->\n
特殊字符----》普通字符,如:\---->\\
\n:换行
\t:制表符
\r:回车键
\f:换页
"""
s4 = "hello\nhfajhg\n364765"
print(s4)
print("\"hello\"")
print("'hello'")
print('"hello"')
s5 = "C:\\Users\\Administrator\\Desktop\\test"
s6 = r"C:\Users\Administrator\Desktop\test"
print(s6)
str1 = "hello"
str2 = "Python"
print(str1 + str2)
print(str1)
print(str2)
str1 = "hello"
str1.upper()
print(str1)
str1 = "this is a test"
str1.replace("test","exam")
print(str1)
print("good" * 3)
print('a' in str1)
"""
evil():将str转换为有效的表达式
upper():将小写字母转换为大写
lower():大---》小
swapcase():大---》小 小----》大
capitalize():首单词的首字母大写,其他全部小写
title():每个单词的首字母大写,其他全部小
ord(),chr()
"""
eval("print('hfajhgkajh')")
print(eval("3 + 4"))
str1 = "This is A TeXT"
print(str1.upper())
print(str1.lower())
print(str1.title())
print(str1.capitalize())
print(str1)
6.大练兵
"""
1.已知字典 dic = {"k1": "v1", "k2": "v2", "k3": "v3"},实现以下功能
"""
dic = {"k1": "v1", "k2": "v2", "k3": "v3"}
a.遍历字典 dic 中所有的key
for key in dic:
print(key)
b.遍历字典 dic 中所有的value
for key in dic:
print(dic[key])
c.循环遍历字典 dic 中所有的key和value
for key,value in dic.items():
print(key,value)
d.添加一个键值对"k4","v4",输出添加后的字典 dic
dic['k4'] = 'v1'
print(dic)
e.删除字典 dic 中的键值对"k1","v1",并输出删除后的字典 dic
dic.pop('k1')
print(dic)
f.删除字典 dic 中 'k5' 对应的值,若不存在,使其不报错,并返回None
aa = dic.pop('k5',None)
print(aa)
g.获取字典 dic 中“k2”对应的值
k2 = dic['k2']
print(k2)
h.已知字典dic2 = {'k1':"v111",'a':"b"} 编写程序,使得dic2 = {'k1':"v111",'k2':"v2",'k3':"v3",'k4': 'v4','a':"b"}
dic = {"k1": "v1", "k2": "v2", "k3": "v3"}
dic2 = {'k1':"v111",'a':"b"}
for key in dic2:
dic[key] = dic2[key]
print(dic)
"""
2.已知列表list1 = [11,22,11,33,44,55,66,55,66],统计列表中
每个元素出现的次数,生成一个字典,结果为{11:2,22:1.....}
"""
list1 = [11,22,11,33,44,55,66,55,66]
dict2 = {}
for i in list1:
count = list1.count(i)
dict2[i] = count
print(dict2)
"""
3.已知如下列表students,在列表中保存了6个学生的信息,
根据要求完成下面的题目
a.统计不及格学生的个数
b.打印不及格学生的名字和对应的成绩
c.统计未成年学生的个数
d.打印手机尾号是8的学生的名字
"""
students = [
{'name': '小花', 'age': 19, 'score': 90, 'gender': '女', 'tel':
'15300022839'},
{'name': '明明', 'age': 20, 'score': 40, 'gender': '男', 'tel':
'15300022838'},
{'name': '华仔', 'age': 18, 'score': 90, 'gender': '女', 'tel':
'15300022839'},
{'name': '静静', 'age': 16, 'score': 90, 'gender': '不明', 'tel':
'15300022428'},
{'name': 'Tom', 'age': 17, 'score': 59, 'gender': '不明', 'tel':
'15300022839'},
{'name': 'Bob', 'age': 18, 'score': 90, 'gender': '男', 'tel':
'15300022839'}
]
count1 = 0
dict2 = {}
count2 = 0
list4 = []
for i in range(len(students)):
if students[i]['score'] < 60:
count1 += 1
dict2[students[i]['name']] = students[i]['score']
if students[i]['age'] < 18:
count2 += 1
if students[i]['tel'][-1] == '8':
list4.append(students[i]['name'])
print('不及格学生人数 %d' % (count1))
print(dict2)
print('未成年学生的个数 %s' % (count2))
print('手机尾号是8的学生的名字',list4)
e.打印最高分和对应的学生的名字
dict5 = {}
max_score = students[0]['score']
for i in range(len(students)):
if max_score < students[i]['score']:
max_score = students[i]['score']
for i in range(len(students)):
if max_score == students[i]['score']:
dict5[students[i]['name']] = students[i]['score']
print('最高分和对应的学生的名字',dict5)
f.删除性别不明的所有学生
new_students = []
for i in range(len(students)):
if students[i]['gender'] != '不明':
new_students.append(students[i])
print(new_students)
g.将列表按学生成绩从大到小排序
for i in range(len(students)):
for j in range(i,len(students)):
if students[i]['score'] < students[j]['score']:
students[i],students[j] = students[j],students[i]
print(students)
"""
4.写一个学生作业情况录入并查询的小程序
a.录入学生作业情况:字典添加
b.查看学生作业情况:字典查询
c.录入时允许输入3次,3次输入不正确提示失败次数过多,禁止继续录入
"""
students = {}
count = 0
while True:
choice = input('请选择1.录入 2.查询')
if choice.isdigit():
choice = int(choice)
count = 0
if choice == 1:
while count < 3:
name1 = input('学生姓名')
scores = input('学生成绩')
if scores.isdigit():
students[name1] = scores
else:
count += 1
else:
print('录入错误次数过多,禁止继续录入')
elif choice == 2:
name2 = input('请输入要查询学生的姓名')
if name2 in students.keys():
print(name2,students[name2])
else:
print('您要查询的学生不在范围内,请重新输入')
else:
print('输入有误,请重新输入')
"""
5.用三个元组表示三门学科的选课学生姓名(一个学生可以同时选多门课)
"""
subject1 = ('王一','赵四','张三','李五','薛二')
subject2 = ('王一','张三','李五','熊大')
subject3 = ('李五','熊大','熊二','光头强')
num1 = len(set(subject1 + subject2 + subject3))
print(num1)
set1 = set(subject1)
set2 = set(subject2)
set3 = set(subject3)
print(len(set1)+len(set2)+len(set3))
set1.update(set2)
set3.update(set1)
print(len(set3))
listb = []
for name in subject1:
if name not in subject2 and name not in subject3:
listb.append(name)
print(len(listb),listb)
print(set1 -(set2|set3))
listc1 = []
listc2 = []
listc3 = []
for name in subject1:
if name not in subject2 and name not in subject3:
listc1.append(name)
for name in subject2:
if name not in subject1 and name not in subject3:
listc2.append(name)
for name in subject3:
if name not in subject2 and name not in subject1:
listc3.append(name)
print(len(listc1),listc1,len(listc2),listc2,len(listc3),listc3)
subject1 = set(subject1)
subject2 = set(subject2)
subject3 = set(subject3)
set1 = (subject1-subject2)-subject3
set2 = (subject2-subject1)-subject3
set3 = (subject3-subject2)-subject1
print(len(set1),set1,len(set2),set2,len(set3),set3)
print(set1 - set2 -set3)
print(set2-set1-set3)
print(set3-set1-set2)
set1 = (subject1&subject3)-subject2
set2 = (subject2&subject3)-subject1
set3 = (subject3&subject1)-subject2
print(len(set1),set1,len(set2),set2,len(set3),set3)
sete = subject3&subject2&subject1
print('选了三门学科的学生人数%s,分别是%s'%(len(sete),sete))
|