python字典和集合总结

字典的增和改

1.字典[键] = 值

1.1如果键存在时修改键对应的值,不存在则添加键值对

cat = {'name':'加菲','age':3,'color':'白色'}


## 添加
cat['breed'] = '蓝猫'
print(cat)  ##{'name': '加菲', 'age': 3, 'color': '白色', 'breed': '蓝猫'}
## 修改
cat['age'] = 2
print(cat)  ##{'name': '加菲', 'age': 2, 'color': '白色', 'breed': '蓝猫'}

## 添加 setdefault 方法,如果存在的时候不会修改,没有才添加
cat.setdefault('weight',5)
print(cat)
## {'name': '加菲', 'age': 2, 'color': '白色', 'breed': '蓝猫', 'weight': 5}
cat.setdefault('age',4)
print(cat)
## {'name': '加菲', 'age': 2, 'color': '白色', 'breed': '蓝猫', 'weight': 5}

setdefault 方法实例

练习:在students中没有分数的学生中添加分数对应的键值对,分数值为零

students = [
    {'name': 'stu1', 'tel': '1234', 'score': 89},
    {'name': 'stu2', 'tel': '465', 'score': 80},
    {'name': 'stu3', 'tel': '678'},
    {'name': 'stu3', 'score': 78},
    {'name': 'stu4', 'tel': '234'}
]

for item in students:
    item.setdefault('score',0)
print(students)

字典的删除 - 删除键值对

1.1 del 方法 - del 字典[键]

1.1.1 如果不给键,会删除整个字典

1.1.2 删除指定键对应的键值对,键不存在会报错

cat = {'name':'加菲','age':3,'color':'白色'}
print(cat)
##{'name': '加菲', 'age': 3, 'color': '白色'}
del cat['color']
print(cat)
##{'name': '加菲', 'age': 3, 'color': '白色'}

1.2 pop 方法 - 字典.pop(键)

1.2.1 - 取出字典指定键对应的值

1.3.1 - 如果键不存在会报错

cat = {'name':'加菲','age':3,'color':'白色'}
del_value = cat.pop('color')
print(cat)
print(del_value)

字典的相关操作

1.1 字典不支持 +,*,也不支持比较大小的运算符,支持 == ,!=

1.2 in 或 not in 判断字典中是否存在指定键

1.3 键 in / not in 字典

dict1 = {'a':10,'b':20,'c':30}
print(10 in dict1)  ##False
print('a' in dict1)  ##True

1.4 相关函数

1.4.1 len 获取长度

1.4.2 dict(数据) -

1)数据本身是一个序列,
2)序列中的元素是有且只有两个元素的小序列
3)小序列的第一个元素是不可以改变的数据
data = [('a',10),('b',20)]
print(dict(data))
## {'a': 10, 'b': 20}

data2 = ['ab',range(2),[10,20]]
print(dict(data2))
## {'a': 'b', 0: 1, 10: 20}

## data2 = ['abc',range(2),[10,20]] ##报错

1.5 字典转换成列表和元组

dict2 = {'a':10,'b':20,'c':30}
print(list(dict2))  ##list 只拿到字典的键
## ['a', 'b', 'c']
print(tuple(dict2))  ##tuple 也只拿到字典的键
## ('a', 'b', 'c')

1.6 字典相关方法

1.6.1 clear - 清空

1)字典.clear()
dict2 = {'a':10,'b':20,'c':30}
dict2.clear()
print(dict2)

1.6.2 copy - 复制产生一个一样的新字典

1)字典.copy()
dict2 = {'a':10,'b':20,'c':30}
dict3 = dict2.copy()
print(dict3)

1.6.3 items,keys,values

1)字典.keys() - - 获取字典键
dict2 = {'a':10,'b':20,'c':30}
print(dict2.keys())
## dict_keys(['a', 'b', 'c'])
2)字典.values() - 获取字典值
dict2 = {'a':10,'b':20,'c':30}
print(dict2.values())
## dict_values([10, 20, 30])
3)字典.items() - 取出元素
dict2 = {'a':10,'b':20,'c':30}
print(dict2.items())
## dict_items([('a', 10), ('b', 20), ('c', 30)])

1.6.4 update

1)字典.update(序列)
2)将序列中的所有元素都添加到字典中(如果存在则覆盖)
3)序列必须是字典或者是能转换成字典的序列
dict2 = {'a':10,'b':20,'c':30}
dict3 = {'d':40}
print(dict2)
## {'a': 10, 'b': 20, 'c': 30}
dict2.update(dict3)
print(dict2)
## {'a': 10, 'b': 20, 'c': 30, 'd': 40}
dict2.update(['xy','mn'])
print(dict2)
## {'a': 10, 'b': 20, 'c': 30, 'd': 40, 'x': 'y', 'm': 'n'}
dict2.update({'d':50,'e':60})
print(dict2) ## 键'd'存在,值被修改,'e'被添加
## {'a': 10, 'b': 20, 'c': 30, 'd': 50, 'x': 'y', 'm': 'n', 'e': 60}

1.7 字典的推导式

1.7.1 {键的表达式:值的表达式 for 变量 in 序列}

练习1. 通过字典的推导式交换字典的键和值
dict1 = {'a':10,'b':20}
dict2 = {dict1[key]:key for key in dict1}
print(dict2)

1.7.2 {键的表达式:值的表达式 for 变量 in 序列 if 条件语句}

集合 - set

1 集合是容器型数据 - 将 {}作为容器的标志

1.1 多个元素用逗号隔开

1.2 集合是可变的,并且集合是无序的

1.3 集合的元素是不可变的数据,且是唯一的

2.1 空集合

set1 = set()
print(type(set1),set1,len(set1))
##<class 'set'> set() 0

2.2 集合无序

print({1,2,3}=={3,1,2})
## True

2.3 元素必须是不可变的数据

set2 = {1,'abc',(2,3)}
print(set2)
## {(2, 3), 1, 'abc'}

## set3 = {1,'abc',[2,3]}  ##报错

2.4 元素是唯一的

set4 = {1,2,3,2,4,1,5,4,1}
print(set4)
## {1, 2, 3, 4, 5}

3 集合元素的增删改查

3.1 查 - 遍历

for 元素 in 集合
    循环体
set1 = {23,90,80,92,77}
for x in set1:
    print(x)

3.2 增

3.2.1 集合.add(元素) 在集合中添加指定元素
set1 = {23,90,80,92,77}
set1.add(34)
print(set1)
## {34, 77, 80, 23, 90, 92}
3.2.2 集合.update(序列) - 将序列中的元素全部添加到集合中
set1 = {23,90,80,92,77}
set1.update('abc')
print(set1)
## {'b', 'a', 77, 80, 'c', 23, 90, 92}

3.3 删

3.3.1 集合.remove(元素)
删除指定元素,元素不存在会报错
set1 = {23,90,80,92,77}
set1.remove(77)
print(set1)
## set1.discard(1)  ## 报错,元素不存在
3.3.2 集合.discard(元素)
删除指定元素,元素不存在不会报错
set1 = {23,90,80,92,77}
set1.discard(90)
print(set1)

## set1.discard(1)  ## 不会报错

4 改 - 无法直接修改元素的值

4.1 方法1:将要修改的元素删除,添加需要的元素

将小写的a改成大写的A

set5 = {'a','b','c'}
set5.remove('a')
set5.add('A')
print(set5)

5 数学集合运算 : & (交集),|(并集),-(差集),^(对称差集),>/<(真子集),>=,<=(子集)

5.1 集合1 & 集合2 - 获取两集合的公共元素

set1 = {1,2,3,4,5,6,7}
set2 = {5,6,7,8,9,10,11}
print(set1 & set2)
## {5, 6, 7}

5.2 集合1 | 集合2 - 合并两个集合

set1 = {1,2,3,4,5,6,7}
set2 = {5,6,7,8,9,10,11}
print(set1 | set2)
## {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}

5.3 集合1 - 集合2 集合1减去集合1中包含在集合2的元素

set1 = {1,2,3,4,5,6,7}
set2 = {5,6,7,8,9,10,11}
print(set1 - set2)
## {1, 2, 3, 4}
print(set2 - set1)
## {8, 9, 10, 11}

5.4 集合1 ^ 集合2 将两个集合合并,去掉公共部分

set1 = {1,2,3,4,5,6,7}
set2 = {5,6,7,8,9,10,11}
print(set1 ^ set2)

5.5 集合1 >/< 集合2 -> 判断集合2是否是集合1的真子集/判断集合1是否是集合2的真子集

作业1

1.定义一个列表,在列表中保存6个学生的信息(学生信息中包括: 姓名、年龄、成绩(单科)、电话、性别(男、女、不明) )

list1 = [
    {'姓名':'张三','age':18,'score':99,'tel':'1828','sex':'男'},
    {'姓名':'李四','age':20,'score':88,'tel':'1824','sex':'男'},
    {'姓名':'王五','age':21,'score':49,'tel':'1823','sex':'女'},
    {'姓名':'小花','age':18,'score':87,'tel':'1825','sex':'女'},
    {'姓名':'小明','age':23,'score':56,'tel':'1826','sex':'不明'},
    {'姓名':'小毛','age':25,'score':78,'tel':'1827','sex':'男'},
]

1. 1统计不及格学生的个数

count = 0
for item in list1:
    if item['score']<60:
        count+=1
print("不及格学生个数为:",count)

1. 2打印不及格学生的名字和对应的成绩

for item in list1:
    if item['score']<60:
        print(item['姓名'],item['score'])

1.3 打印手机尾号是8的学生的名字

for item in list1:
    if int(item['tel']) % 10 == 8:
        print(item['姓名'],item['tel'])

1.4 打印最高分和对应的学生的名字

max_score = 0
for item in list1:
    if item['score'] > max_score:
        max_score = item['score']
for i in list1:
    if i['score'] == max_score:
        print(i['姓名'],i['score'])

1.5 删除性别不明的所有学生

for item in list1:
    if item['sex'] == '不明':
        list1.remove(item)
print(list1)

1.6 将列表按学生成绩从大到小排序(挣扎一下,不行就放弃)

for x in range(len(list1)):
    i = 0
    j = 1
    while j<len(list1):
        if list1[i]['score'] < list1[j]['score']:
            k = list1[j]
            list1[j] = list1[i]
            list1[i] = k
        i+=1
        j+=1
print(list1)

2.用三个集合表示三门学科的选课学生姓名(一个学生可以同时选多门课)

chinese = {'小明', '小花', '张三', '王五','赵六'}
english = {'小翠', '李四', '张三', '王五','赵六'}
math = {'小明', '李四', '王五','赵六'}

2.1 求选课学生总共有多少人

print('选课总人数为:',len(chinese|english|math))

2.2 求只选了第一个学科的人的数量和对应的名字

count = 0
set1 = set()
for item in chinese:
    if item not in english and item not in math:
        count+=1
        set1.add(item)
print('只选了第一个学科的数量为:',count,'名字有:',set1)

2.3 求只选了一门学科的学生的数量和对应的名字

set2 = (chinese|english|math)-(chinese&english)-(chinese&math)-(english&math)
print("学生数量为:",len(set2),"名字有",set2)

2.4 求只选了两门学科的学生的数量和对应的名字

count =0
set3 = set()
for item in chinese:
    if (item in english and item not in math) or (item in math and item not in english):
        count+=1
        set3.add(item)
print('只选了两门学科的人数为:',count,'名字有:',set3)

2.5 求选了三门学生的学生的数量和对应的名字

count =0
set4 = set()
for item in chinese:
    if item in english and item in math:
        count+=1
        set4.add(item)
print("选了三门学生的数量为:",count,'名字有:',set4)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

azured_xu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值