当前位置: 首页 > java >正文

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])
http://www.xdnf.cn/news/2785.html

相关文章:

  • 基于docker部署mssqlserver : mcr.microsoft.com/mssqlserver:2022-latest
  • 第十八节:开放性问题-Vue生态未来趋势
  • kubernetes常用命令 k8s指令大全
  • 【205】Python3 实现整数和IP地址字符串互相转换
  • 【读书笔记】机器行为与具身智能
  • pywinauto操作Windows应用
  • VUE3:封装一个评论回复组件
  • 【环境配置】Mac电脑安装运行R语言教程 2025年
  • 如何评价 DeepSeek 的 DeepSeek-V3 模型?
  • 【优选算法 | 二分查找】二分查找算法解析:如何通过二段性优化搜索效率
  • Python项目-支持自然语言处理
  • Docker和K8s面试题
  • Nacos 3.0 上线 MCP Registry,支持 MCP 服务注册到发现全流程管理
  • 从零开始学习车联网相关知识-学习计划
  • YUM/DNF管理工具
  • 蓝桥杯2025年第十六届省赛真题-可分解的正整数
  • 使用Optional优雅处理Null检查
  • 赋能航天教育:高校卫星仿真教学实验平台解决方案
  • Github两种鉴权模式PAT与SSH
  • CMU-15445(1)——环境搭建
  • python上测试neo4j库
  • 注意力机制:从 MHA、MQA、GQA、MLA 到 NSA、MoBA
  • Mysql索引
  • LeetCode【剑指offer】系列(动态规划篇)
  • VBA快速创建Excel中数据模型的数据连接
  • C++ 部署的性能优化方法
  • 网络拓扑模型相关题目-1
  • Lustre/Scade 语言时序算子与形式化验证的联系
  • 从暴力到优化:解决「分数严格小于k的子数组数目」问题
  • 硬件加密+本地部署,大模型一体机如何打造AI安全护城河?