Python-Part2-集合、字典与推导式
Python-Part2-集合、字典与推导式
1. set集合
⽆序,去掉重复数据。
set1 = {1,2,3,4,5,5,4,3,2,1}print(type(set1))print(set1)set2.add(66666)set2.remove(55)#不能使用下标访问set,所以修改操作一般为remove操作 + add操作
2.dict 字典
字典( dict )是 Python 中另⼀个⾮常有⽤的内置数据类型。
字典是键 (key) : 值 (value) 的 集合。
在同⼀个字典中,键 (key) 必须是唯⼀的。
创建空字典使⽤ { } 。
补充:tuple (元组)只读的列表。
tuple1 = (1,2,34,5,6)
print(type(tuple1))
print(tuple1[3]) for i in tuple1: print(i)
3.练习小测
1.获取字典中的值:获取下列字典键为 'history' 的值sampleDict = {"class":{"student":{"name":"Mike","marks":{"physics":70,"history":80}}}}
sampleDict = {"class":{"student":{"name":"Mike","marks":{"physics":70,"history":80}}}}
print(sampleDict["class"]["student"]["marks"]["history"])
2.请将元组 v1 = (11,22,33) 中的所有元素追加到列表 v2 = [44,55,66] 中
v1 = (11,22,33);v2 = [44,55,66]
v2.extend(list(v1))
print(v2)
3.已知列表:list1 = ['life','is','short'] list2 = ['you','need','python'] list3 = [1,2,3,4,5,3,4,2,1,5,7,9]完成以下操作:(1)把上述三个列表构造为⼀个集合 set1(2)输出集合的⻓度(3)把python从集合中移除
list1 = ['life','is','short'];list2 = ['you','need','python'];list3 = [1,2,3,4,5,3,4,2,1,5,7,9]
list4 = [];list4.extend(list1);list4.extend(list2);list4.extend(list3)
set1 =set(list4)
print(set1)
print(len(set1))
set1.remove('python')
print(set1)
4.已知列表li= [11,22,100,33,44,66,55,77,88,99,90] ,将所有⼤于 66 的值保存⾄字典的第⼀个key对应的列表中,将⼩于 66 的值保存⾄第⼆个key对应的列表中。输出结果:{'key1':[100,77,88,99,90],'key2':[11,22,33,44,55]}
li= [11,22,100,33,44,66,55,77,88,99,90]
out = {'key1':[],'key2':[]}
a =[];b=[]
for i in li :if i > 66 :a.append(i)else :b.append(i)out['key1'] = a;out['key2'] = b
print(out)
5.已知列表list1 = [11,22,11,33,44,55,66,55,66],统计列表中每个元素出现的次数,⽣成⼀个字典输出结果:{11:2,22:1.....}注:顺序不要求
list1 = [11,22,11,11,11,33,44,55,66,55,66]
out = {}
for i in set(list1) :a=0for j in list1 :if i == j :a+=1out[i] = a
print(out)
6.已知字典d1={"subjects":[{"rate":"7.4","cover_x":640},{"rate":"6.0","cover_x":1080}]}处理显⽰成如下格式输出:7.4 640
6.0 1080
d1={"subjects":[{"rate":"7.4","cover_x":640},{"rate":"6.0","cover_x":1080}]}
print(d1["subjects"][0]["rate"],d1["subjects"][0]["cover_x"])
print(d1["subjects"][1]["rate"],d1["subjects"][1]["cover_x"])
7.已知如下数据d1 = { '192.168.1.1':{'cpu':'0.23','内存':'16','硬盘':'500'}, '192.168.1.2':{'cpu':'3.22','内存':'64','硬盘':'700'}, '192.168.1.3':{'cpu':'1.99','内存':'32','硬盘':'800'} }处理显⽰成如下格式输出:
192.168.1.1: cpu 0.23 内存 16 硬盘 500
192.168.1.2: cpu 3.22 内存 64 硬盘 700
192.168.1.3: cpu 1.99 内存 32 硬盘 800
d1 = { '192.168.1.1':{'cpu':'0.23','内存':'16','硬盘':'500'}, '192.168.1.2':{'cpu':'3.22','内存':'64','硬盘':'700'}, '192.168.1.3':{'cpu':'1.99','内存':'32','硬盘':'800'} }
for i in d1 :print(i+":"+' cpu '+d1[i]['cpu']+' 内存 '+d1[i]['内存']+' 硬盘 '+d1[i]['硬盘'])
8.有字符串"k: 1|k1:2|k2:3 |k3 :4" 处理成字典 {'k':1,'k1':2,'k3':4}注:字符串替换使⽤replace函数
n ="k: 1|k1:2|k2:3 |k3 :4"
n.replace(" ")("")
n1 = n.split("|")
out ={}
for i in n1 :if i.count(" ") == 1 :i1 =list(i)i1.remove(" ")i ="".join(i1)out[i[0:i.find(":")]] = i[i.find(":")+1:]
out.pop("k2")
print(out)
4.推导式
输⼊源:range list tuple set dict
输出源:list tuple set dict
推导式格式为:表达式 for 变量 in 输⼊源 if 条件
推导式格式为:表达式 for 变量 in 输⼊源 if 条件 for 变量 in 输⼊源 if 条件
# 给定一个列表,将每一位数字变成它的平方 alist = [1, 2, 3, 4, 5, 6, 7]# 输出结果:[1, 4, 9, 16, 25, 36, 49]alist = [1, 2, 3, 4, 5, 6, 7]print([i**2 for i in alist])print([i**2 for i in alist if i+2>5])print({i**2 for i in alist})print(tuple((i**2 for i in alist)))print({i**2:f"test{i}" for i in alist})#推导 30 以内可以被 3 整除的整数为列表:
print([i for i in range(30) if i % 3 == 0])
5.课后习题
1.⽣成⼀个存放1-100之间个位数为3的数据列表
print([i for i in range(1,100) if i%10 == 3])
2.利⽤列表推导式将已知列表中的整数提取出来[17, 98, 34, 21] list_two = [True, 17, "hello", "bye", 98, 34, 21]
list_two = [True, 17, "hello", "bye", 98, 34, 21]
print([i for i in list_two if type(i) == int])
3.list_three=["good", "nice", "see you", "bye"],根据列表利⽤推导式存放指定列表中字符串的⻓度如下{'good':4, 'nice':4, 'see you':7, 'bye':3}
list_three=["good", "nice", "see you", "bye"]
print({i:len(i) for i in list_three})
4.⽣成⼀个列表,其中的元素为'0-1','1-2','2-3','3-4','4-5'
print([str(i)+str(-i-1) for i in range(6)])
5.已知数据t1=((1,100),(2,30),(3,80),(4,234))
推导成列表[100,30,80,234]
推导成字典{1: 100, 2: 30, 3: 80, 4: 234}
推导成列表[{'name': 1, 'value': 100}, {'name': 2, 'value': 30}, {'name': 3, 'value': 80}, {'name': 4, 'value': 234}]
t1=((1,100),(2,30),(3,80),(4,234))
print([i[1] for i in t1])
print({i[0]:i[1] for i in t1})
print([{'name':i[0], 'value': i[1]} for i in t1])
6.已知如下列表students,在列表中保存了6个学⽣的信息,根据要求完成下⾯的题⽬students = [ {'name': '⼩花', 'age': 19, 'score': 90, 'gender': '⼥', 'tel':'15300022839'}, {'name': '明明', 'age': 20, 'score': 40, 'gender': '男', 'tel':'15300022838'}, {'name': '华仔', 'age': 18, 'score': 100, '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'} ]
打印学⽣分数列表
打印⼿机尾号是8的学⽣的名字列表
打印不及格的同学的所有信息列表,效果如下:
['明明', 20, 40, '男', '15300022838', 'Tom', 17, 59, '不明', '15300022839']
students = [ {'name': '⼩花', 'age': 19, 'score': 90, 'gender': '⼥', 'tel':'15300022839'}, {'name': '明明', 'age': 20, 'score': 40, 'gender': '男', 'tel':'15300022838'}, {'name': '华仔', 'age': 18, 'score': 100, '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': '男',
print([i['score'] for i in students for j in i])
print([i[j] for i in students for j in i if i['score'] <60])
print([i['name'] for i in students for j in i if int(i['tel']) %10 ==8])