python第二周day3(9.24)
1、day7字典作业更改版
# 定义一个列表,在列表中保存6个学生的信息(学生信息中包括: 姓名、年龄、成绩(单科)、电话、性别(男、女、不明) )
students = [
{'name': '晨晨', 'age':18, 'score': 78, 'tel': '123', 'gender': '男'},
{'name': '陈来', 'age':20, 'score': 80, 'tel': '321', 'gender': '不明'},
{'name': '陈昕', 'age':28, 'score': 98, 'tel': '653', 'gender': '女'},
{'name': '小新', 'age':32, 'score': 65, 'tel': '783', 'gender': '男'},
{'name': '小明', 'age':17, 'score': 24, 'tel': '988', 'gender': '女'},
{'name': '小红', 'age':14, 'score': 54, 'tel': '903', 'gender': '男'}
]
# 1. 统计不及格学生的个数
count = 0
for stu in students:
if stu['score'] < 60:
count += 1
print('1)不及格学生的个数:', count) # 2
# 2.打印不及格学生的名字和对应的成绩
print('2)不及格学生的名字和对应的成绩')
for stu in students:
score = stu['score'] #先保存成绩数据
if score < 60:
print(stu['name'], score) # 小明 24 小红 54
# 3.统计未成年学生的个数
# **4.打印手机尾号是8的学生的名字
# 方法一
print('4)手机尾号是8的学生的名字:')
for stu in students:
if stu['tel'][-1] == '8':
print(stu['name']) # 小明
# 方法二
for stu in students:
if int(stu['tel']) % 10 == 8:
print(stu['name']) # 小明
# 5)打印最高分和对应的学生的名字
print('5)最高分和对应的学生的名字:')
# 方法一:
# **第一次循环获取最高分
max_score = students[0]['score']
for stu in students[1:]:
score = stu['score']
if score > max_score:
max_score = score
# 第二次循环找到分数和最高分相等的所有学生的姓名
for stu in students:
if stu['score'] == max_score:
print(stu['name'], max_score) # 陈昕 98
# **方法二:
max_score = students[0]['score']
names = [students[0]['name']]
for stu in students[1:]:
score = stu['score']
if score == max_score:
names.append(stu['name'])
elif score > max_score:
max_score = score
names.clear()
names.append(stu['name'])
print(names, max_score) # ['陈昕'] 98
# 6.删除性别不明的所有学生(使用提出) 老师举例(下标遍历--倒着取)
#方法一(删除)
print('6)删除性别不明的所有学生:')
# for stu in students[:]:
# if stu['gender']== '不明':
# students.remove(stu)
# print(students)
# 方法二,推导式(提取)
# new_students = [stu for stu in students if stu['gender']!= '不明']
# print(new_students)
#举例说明
# nums = [89,90, 10, 11, 30, 60]
# temp = nums.copy()
# for x in nums[:]:#产生一个新的一样的nums ,相当于temp ,nums.copy() 遍历一个删除另外一个
# if x < 60:
# nums.remove(x)
# print(nums)
# 7.将列表按学生成绩从大到小排序
students.sort(key=lambda item: item['score'], reverse=True)
print(students)
# 用三个集合表示三门学科的选课学生姓名(一个学生可以同时选多门课)
math = {'陈来', '小张', '小溪'}
history = {'陈来', '小新', '小智', '小张'}
english = {'小李', '小丽', '小智', '小张'}
# 1. 求选课学生总共有多少人
s1 = math | history | english
print(s1, '选课学生人数:', len(s1))
# 2. 求只选了第一个学科的人的数量和对应的名字
s2 = math - history - english
print('只选了第一个学科的人的数量:', len(s2))
print('只选了第一个学科的名字:', s2)
# 3. 求只选了一门学科的学生的数量和对应的名字
# 方法一
s3 = (math - history - english) | (history - math - english) | (english - history - math)
print('只选了一门学科的学生的数量:', len(s3))
print('只选了一门学科的学生的名字:', s3)
# 方法二
s3 =(math ^ history ^ english) - (math & history & english)
print(s3)
# 5. 求选了三门学生的学生的数量和对应的名字
math = {'陈来', '小张', '小溪'}
history = {'陈来', '小新', '小智', '小张'}
english = {'小李', '小丽', '小智', '小张'}
s5 = math & history & english
print('选了三门学生的学生的数量:', len(s5))
print('选了三门学生的学生的名字:', s5)
# 4. 求只选了两门学科的学生的数量和对应的名字
# result3 = math & history & english
# result1 = (math & history ) | (math & english) | (english & history)
# result4 = result1 - result3
# print(result4, len(result4))
s4 =s1 - s3 - s5
print('只选了两门学科的学生的数量:', len(s4))
print('只选了两门学科的学生的名字:', s4)
2、字典相关操作和方法
1.字典不支持 +、*、<,>,<=,>= 比较大小
2.字典支持: == 、!=
print({'a': 10, 'b': 20} == {'b': 20, 'a': 10}) # True
3.in 和 not in
“”"
键 in 字典 - 判断字典中是否存在指定的键“”"
d1 = {'a': 10, 'b': 20, 'c': 30}
print(30 in d1) # False
print('b' in d1) # True
4.dict(类型转换)
“”"
dict(数据) - 将数据转换成字典数据的要求:1)数据本身是一个序列
2)序列中的元素必须是长度为2的小序列(键值对)
3)小序列的第一个元素必须是不可变的数据“”"
注意:将字典转换成理部或者元组的时候,将字典的键作为列表,元组中的元素
result = dict([(1, 2), 'ab', ['a', 100]]) # 转换为字典
print(result) # {1: 2, 'a': 100} 重复了保存一个
result = dict([(1, 2), 'bb', ['a', 100]])
print(result) # {1: 2, 'b': 'b', 'a': 100}
# 注意:将字典转换成理部或者元组的时候,将字典的键作为列表,元组中的元素
d1 = {'a': 10, 'b': 20, 'c': 30}
print(list(d1)) # 转换的是键 ['a', 'b', 'c']
t2 = ((1, 2), 'a1', [3, 9])
result = dict(t2)
print(result) # {1: 2, 'a': '1', 3: 6}
5.相关方法
1)字典.clear() - 清空字典
d1.clear()
print(d1)
- 字典.copy() -
stu1 = {'name': '小明', 'gender':'男', 'age': 18}
stu2 = stu1.copy()
print(stu2)
stu2['name'] = '张三'
print(stu2, stu1)
# stu3 = stu1
# print(stu3)
# stu3['name']= '李思'
# print(stu3, stu1)
- 字典.items() - 将字典中的元素转换成元组,返回一个新的序列
{‘name’: ‘小明’, ‘gender’: ‘男’, ‘age’: 18} -> [(‘name’, ‘小明’)]
{键1:值1,键2:值2} ->[(键1,值1),(键2,值2)]- 字典推导式:{键值对 for 变量 in 序列}、{键值对 for 变量 in 序列 if 条件}
stu1 = {'name': '小明', 'gender':'男', 'age': 18}
result = stu1.items()
print(result) # dict_items([('name', '小明'), ('gender', '男'), ('age', 18)])
print(list(result)) # 任何序列都可以转换成列表 [('name', '小明'), ('gender', '男'), ('age', 18)]
# 练习:使用列表推导式,将一个字典的值全部乘以10
d2 = {'a': 2, 'b': 34, 'c': 21}
# {'a': 20, 'b': 340, 'c': 210}
d3 = dict([(x, y*10) for x, y in d2.items()]) # [(x,y),(x1,y1)]
print(d3) # {'a': 20, 'b': 340, 'c': 210}
# 字典推导式:{键值对 for 变量 in 序列}、{键值对 for 变量 in 序列 if 条件}
d2 = {'a': 2, 'b': 34, 'c': 21}
new_d2 = {x: d2[x]*10 for x in d2}
print(new_d2) # {'a': 20, 'b': 340, 'c': 210}
x = (10, 20)
x, y = (10, 20)
d3 = {key: value*10 for key,value in d2.items()} # 转换为序列-->元组
print(d3) # {'a': 20, 'b': 340, 'c': 210}
# 练习2:使用推导式,交换字典的键和值
d2 = {'a': 2, 'b': 34, 'c': 21}
#
new_d2 = {d2[x]: x for x in d2}
print(new_d2) # {2: 'a', 34: 'b', 21: 'c'}
new_d2 = {value: key for key, value in d2.items()}
print(new_d2)
new_d2 = dict([(y, x) for x, y in d2.items()])
print(new_d2)
4)字典.keys() - 获取字典所有的键,返回一个新的序列
d2 = {'a': 2, 'b': 34, 'c': 21}
print(d2.keys()) # dict_keys(['a', 'b', 'c'])
5)字典.values() - 获取字典所有的值,返回一个新的序列
print(d2.values()) # dict_values([2, 34, 21])
6)字典.setdefault(键,值) - 在字典中添加一个键值对(如果字典中已经存在键值对,不会执行修改操作)
字典[键] = 值
d1 = {'a': 10}
print(d1) # {'a': 10}
d1['b'] = 20
print(d1) # {'a': 10, 'b': 20}
d1.setdefault('c', 30)
print(d1) # {'a': 10, 'b': 20, 'c': 30}
d1 = {'a': 10}
d1.setdefault('a', 100)
print(d1) # {'a': 10}
d1['a'] = 100
print(d1) # {'a': 100}
d3 = {'a': 10, 'b': 20, 'c': 30}
d3.setdefault('d',190)
print(d3)
goods_list = [
{'name': '泡面', 'price': 4, 'discount': 0.9, 'count': 100},
{'name': '火腿肠', 'price': 2, 'count': 120},
{'name': '矿泉水', 'price': 1, 'count': 500},
{'name': '面包', 'price': 5, 'count': 120, 'discount': 0.75}
]
for goods in goods_list:
goods.setdefault('discount', 1)
print(goods_list) # 直接添加'discount': 1
for goods in goods_list:
goods['discount'] = 1
print(goods_list)
7)字典.update(序列) - 将序列中的元素全部添加到字典中
序列 - 是字典或者是能转换成字典的序列
d1 = {'a': 10, 'b': 20}
d2 = {'name': '小明', 'age': 18, 'a': 200}
d1.update(d2)
print(d1) # {'a': 200, 'b': 20, 'name': '小明', 'age': 18}
d1.update(['mn', (1, 2)])
print(d1) # {'a': 200, 'b': 20, 'name': '小明', 'age': 18, 'm': 'n', 1: 2}
3、集合
1.什么是集合(set)
“”"
集合是容器型数据类型(序列);将{}作为容器的标志里面多个元素用逗号隔开:{元素1,元素2,元素3…}
集合是可变的;集合无序的
元素 - 必须是不可变的数据;唯一
“”"
- 空集合
s1 = set()
print(len(s1), type(s1)) # 0 <class 'set'>
- 集合元素必须是不可变的数据 (集合无序)
s2 = {1, 'abc', (23,4)} # 数字,字符串,元组不可变数据
print(s2) # {(23, 4), 1, 'abc'}
3)集合无序
print({1, 2, 3} == {3, 2, 1}) # True(顺序不影响结果)
4)元素是唯一的
s3 = {1, 2, 3, 1, 1, 4}
print(s3) # {1, 2, 3, 4}
names = ['张三', '张三', '李思', '小明']
print(set(names)) # {'李思', '小明', '张三'} 去重,数据
2.集合的增删改查(不支持改,删掉和增加,了解)
1) 查 - 只能遍历(集合无序)
hobby = {'玩游戏', '看电影', '打篮球', '爬山', '做饭'}
for x in hobby:
print(x)
2)增:
集合.add(元素)
集合.update(序列)
hobby.add('游泳')
print(hobby) # {'看电影', '游泳', '爬山', '做饭', '玩游戏', '打篮球'}
hobby.update(('乒乓球', '羽毛球'))
print(hobby) # {'玩游戏', '做饭', '游泳', '羽毛球', '爬山', '乒乓球', '打篮球', '看电影'}
- 删
集合.remove(元素) - 如果元素不存在会报错
集合.discard(元素) - 如果元素不存在不会报错
hobby.remove('做饭')
print(hobby) # {'羽毛球', '爬山', '看电影', '乒乓球', '玩游戏', '打篮球', '游泳'}
hobby.discard('玩游戏')
print(hobby) # {'游泳', '看电影', '乒乓球', '打篮球', '爬山', '羽毛球'}
# hobby.remove('做饭')
hobby.discard('做饭')
4、数学集合运算
python中的集合支持数学集合运算
1.并集 - |
集合1 |集合2 - 将两个集合合并成一个集合
s1 = {1, 2, 3, 4, 5}
s2 = {3, 4, 6, 7, 8}
result = s1 | s2
print(result) # {1, 2, 3, 4, 5, 6, 7, 8}
2.交集 - &
集合1 & 集合2 - 获取两个集合的公共部分,产生一个新的集合
result = s1 & s2
print(result) # {3, 4}
3.差集 - -
集合1 - 集合2 - 获取集合1中去掉包含在集合2中的元素,剩下的元素
s1 = {1, 2, 3, 4, 5}
s2 = {3, 4, 6, 7, 8}
result = s1 - s2
print(result) # {1, 2, 5}
4.对称差集 - ^ -A并B减去A交B
集合1 ^ 集合2 -将两个集合合并,去掉公共部分获取剩下的部分
print(s1^s2) # {1, 2, 5, 6, 7, 8}
5.判断子集关系
子集: >= , <=
真子集: >, <
集合1 > 集合2 - 判断集合2是否是集合1的真子集
集合1 < 集合2 - 判断集合1是否是集合2的真子集
s3 = {10, 20, 30}
# 真子集: {10, 20},{20,30},{10,30},{10},{20},{30},空集
# 子集: {10, 20},{20,30},{10,30},{10},{20},{30},空集,{10, 20, 30}
print({9, 2, 3} > {3, 4}) # False 判断真子集
print({4, 2, 3} > {3, 4}) # True 是真子集
# 练习
# 用三个集合表示三门学科的选课学生姓名(一个学生可以同时选多门课)
math = {'陈来', '小张', '小溪'}
history = {'陈来', '小新', '小智', '小张'}
english = {'小李', '小丽', '小智', '小张'}
# 1. 求选课学生总共有多少人
s1 = math | history | english
print(s1, '选课学生人数:', len(s1))
# 2. 求只选了第一个学科的人的数量和对应的名字
s2 = math - history - english
print('只选了第一个学科的人的数量:', len(s2))
print('只选了第一个学科的名字:', s2)
# 3. 求只选了一门学科的学生的数量和对应的名字
# 方法一
s3 = (math - history - english) | (history - math - english) | (english - history - math)
print('只选了一门学科的学生的数量:', len(s3))
print('只选了一门学科的学生的名字:', s3)
# 方法二
s3 =(math ^ history ^ english) - (math & history & english)
print(s3)
# 5. 求选了三门学生的学生的数量和对应的名字
math = {'陈来', '小张', '小溪'}
history = {'陈来', '小新', '小智', '小张'}
english = {'小李', '小丽', '小智', '小张'}
s5 = math & history & english
print('选了三门学生的学生的数量:', len(s5))
print('选了三门学生的学生的名字:', s5)
# 4. 求只选了两门学科的学生的数量和对应的名字
# result3 = math & history & english
# result1 = (math & history ) | (math & english) | (english & history)
# result4 = result1 - result3
# print(result4, len(result4))
s4 =s1 - s3 - s5
print('只选了两门学科的学生的数量:', len(s4))
print('只选了两门学科的学生的名字:', s4)
本文介绍了Python第二周day3的学习内容,主要包括字典的更新版作业、字典的操作和方法,如不支持的比较操作、键的检查、字典的转换等,以及集合的概念、增删查操作和数学集合运算,如并集、交集、差集和对称差集等。
1450

被折叠的 条评论
为什么被折叠?



