字典和集合

本文详细介绍了Python编程中的字典和集合操作,包括增删改查、相关函数、数学集合运算等,并给出了多个示例。此外,还展示了如何在实际场景中使用这些数据结构,如处理学生信息、统计不及格学生数量、筛选特定属性的学生等。通过对字典和集合的深入理解,能更好地掌握Python编程技巧。
摘要由CSDN通过智能技术生成

字典和集合

1.字典的增删改

'''
1. 增和改
字典[键] = 值  - 当键存在的时候是修改键对应的值:当键不存在的时候添加键值对
字典.setdefault(键,值) - 添加键值对(当键存在的时候不会修改原来的值
'''
cat = {'name': '美美', 'age': 2, 'color': '白色'}
print(cat)   # {'name': '美美', 'age': 2, 'color': '白色'}
#添加
cat['breed'] = '蓝猫'
print(cat)   # {'name': '美美', 'age': 2, 'color': '白色', 'breed': '蓝猫'}

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

cat.setdefault('wejght', 8)
print(cat)  # {'name': '美美', 'age': 3, 'color': '白色', 'breed': '蓝猫', 'wejght': 8}

cat.setdefault('age', 4)
print(cat)  #  {'name': '美美', 'age': 3, 'color': '白色', 'breed': '蓝猫', 'wejght': 8}
练习
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 stu in students:
    stu.setdefault('score', 0)
print(students)
2.- 删除键值对
del 字典[]   - 删除字典中指定键对应的键值段(如果键不存在报错)
字典.pop()   -  取出字典中指定键对应的值

'''
print(cat)  # {'name': '美美', 'age': 3, 'color': '白色', 'breed': '蓝猫', 'wejght': 8}
del cat['color']  # {'name': '美美', 'age': 3, 'breed': '蓝猫', 'wejght': 8}
print(cat)

del_value = cat.pop('breed')
print(cat)  # {'name': '美美', 'age': 3, 'wejght': 8}
print(del_value)   # 蓝猫

2.字典相关的操作和函数

'''
1. 相关操作
字典不支持+,*,也不支持比较大小的运算。支持==,/!=
支持 in 和 not in - 字典的in 和 not in判断的是键是否存在
键 in 字典 
键 not in 字典

'''

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

'''
2.相关函数
len  获取长度
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}



'''
字典转换成列表/元组   
'''
dic2 = {'a': 10, 'b': 20, 'c': 30}
print(list(dic2))   #  ['a', 'b', 'c']

"""
3.字典相关方法
字典.clear()   -  清空
字典.copy()    -  复制原字典产生一个一摸一样的新字典

字典.update(序列)   -  将序列中所有的元素都添加到字典中(如果本身就存在就会覆盖),
序列必须是字典或者能够转换成字典的序列
items,keys,values
字典.keys()  - 获取字典的所有键,返回一个序列()
字典。values() -  获取字典的所有的值
"""
data3 = {'d': 100, 'e': 200}
print(dic2)
dic2.update(data3)
print(dic2)

dic2.update(['xy', 'mn'])
print(dic2)

dic2.update({'d': 1000, 'f': 2000})
print(dic2)

print(dic2.keys())   # dict_keys(['a', 'b', 'c', 'd', 'e', 'x', 'm', 'f'])
print(dic2.values())  # dict_values([10, 20, 30, 1000, 200, 'y', 'n', 2000])
print(dic2.items())  # dict_items([('a', 10), ('b', 20), ('c', 30), ('d', 1000), ('e', 200), ('x', 'y'), ('m', 'n'), ('f', 2000)])

'''
4.字典推导式
{键的表达式:值的表达试for 变量 in 序列}
{键的表达式:值的表达试for 变量 in 序列 if 条件语句}
'''
# 练习:通过字典的推导式交换一个字典的键和值
'''{'a': 10, 'b': 20}'''

dic4 = {'a': 10, 'b': 20}
new_dic4 = {dic4[key]: key for key in dic4}
print(new_dic4)

3.集合

什么是集合(set)

'''
集合是容器:将{}作为容器标志,多个元素用逗号隔开:{元素1,元素2,元素3,....}
集合是可变的:集合无序的:
元素:不可变的数据、元素是唯一的(具备自动去重的功能)
'''
# 1.空集合
set1 = set()
print(type(set1), len(set1))  # <class 'set'> 0

# 2. 集合是无序的
print({1, 2, 3} == {3, 2, 1})  # True

# 3.元素必须是不可变的数据
set2 = {1, 'abc', (2, 3)}  # {(2, 3), 1, 'abc'}
print(set2)


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

# 4. 元素是唯一的
set4 = {1, 1, 2, 2, 3, 4, 4}
print(set4)


# 2.集合元素的增删改查
# 1) 查 - 遍历
'''
for 元素 in 集合:
    循环体

'''
nums = {23, 90, 89, 78}
for x in nums:
    print(x)

# 2)  增
'''
集合.add(元素)  - 在集合中添加指定元素
集合.update(列表) - 将序列中的元素全部添加到集合中
'''
nums.add(45)
print(nums)  # {45, 78, 23, 89, 90}

nums.update('abc')
print(nums)  # {'b', 45, 78, 23, 'a', 89, 90, 'c'}

# 3)删
'''
集合.remove(元素)    -  删除指定元素,如果元素不存在会报错
集合.discard(元素)   -  删除指定元素,如果元素不存在不存在报错
'''

nums.remove(89)   # 删除元素
print(nums)   #  {'b', 'c', 45, 78, 23, 'a', 90}

nums.discard(90)
print(nums)   # {'a', 'c', 'b', 45, 78, 23}

# 4) 改 - 集合无法直接修改元素的值,如果非要修改就将改的元素删除,添加新的元素


# 3.数学集合运算:&(交集)、|(并集)、-(差集)、^(对称差集)、>/<(真子集)、>=/<=(子集)
# 1)集合1 & 集合2 - 获取两个集合的公共元素(获取即在集合1又在集合2里面的元素)
num1 = {1, 2, 3, 4, 5, 6, 7}
num2 = {5, 6, 7, 8, 9}
print(num1 & num2)  #  {5, 6, 7}

# 2)集合1 | 集合2 -  获取两个集合所有的元素
print(num1 | num2)  # {1, 2, 3, 4, 5, 6, 7, 8, 9}

# 3)集合1 - 集合2  - 获取集合1中除了包含在集合2中以外的部分
print(num1 - num2)  # {1, 2, 3, 4}
print(num2 - num1)  # {8, 9}

# 4) 集合1 ^ 集合2  - 将两个集合合并,取中间公告部分
print(num1 ^ num2)   # {1, 2, 3, 4, 8, 9}

# 5) 子集(有可能相等)和真子集(真的比它小)
# 集合1 > 集合2   -> 判断集合2 是否是集合1 的真子集
print({10, 20, 30, 40} > {1, 2})  # False
print({10, 20, 30, 40} > {10, 40})  # True
print({10, 20, 30, 40} > {10, 20, 30, 40})   # False
print({10, 20, 30, 40} >= {10, 20, 30, 40})   # True
  1. 定义一个列表,在列表中保存6个学生的信息(学生信息中包括: 姓名、年龄、成绩(单科)、电话、性别(男、女、不明) )

    class1 = [
        {'name': '小红', 'age': 18, 'score': 90, 'tel': '174', 'sex': '男'},
        {'name': '小白', 'age': 20, 'score': 67, 'tel': '159', 'sex': '女'},
        {'name': '小李', 'age': 17, 'score': 59, 'tel': '178', 'sex': '不明'},
        {'name': '小王', 'age': 19, 'score': 78, 'tel': '167', 'sex': '不明'},
        {'name': '小顾', 'age': 17, 'score': 96, 'tel': '176', 'sex': '男'},
        {'name': '小陈', 'age': 21, 'score': 56, 'tel': '171', 'sex': '女'}
    
    1. 统计不及格学生的个数

      f = 0
      for x in class1:
          if x['score'] < 60:
              f += 1
      print(f)
      
    2. 打印不及格学生的名字和对应的成绩

      for x in class1:
          if x['score'] < 60:
              print(x['score'], x['name'])
      
    3. 打印手机尾号是8的学生的名字

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

      max_x = class1[0]['score']
      for stu in class1[1:]:
          s = stu['score']
          if s > max_x:
              max_x = s
      for stu in class1:
          if stu['score'] == max_x:
              print(stu['name'], max_x)
      
    5. 删除性别不明的所有学生

      for x, stu1 in enumerate(class1.copy()):
          if stu1['sex'] == '不明':
              del class1[x]
              print(stu1)
      
    6. 将列表按学生成绩从大到小排序(挣扎一下,不行就放弃)

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

    1. 求选课学生总共有多少人

      print(language | mathematics | chemistry)
      
    2. 求只选了第一个学科的人的数量和对应的名字

      print(len(language - mathematics - chemistry), language - mathematics - chemistry)
      
    3. 求只选了一门学科的学生的数量和对应的名字

      num1 = (language - mathematics - chemistry) | (mathematics - chemistry - language) | (chemistry - language - mathematics)
      print(len(num1), num1)
      
    4. 求只选了两门学科的学生的数量和对应的名字

      num2 = language & mathematics - chemistry | mathematics & chemistry - mathematics | language & chemistry - mathematics
      print(len(num2), num2)
      
    5. 求选了三门学生的学生的数量和对应的名字

      num3 = language & mathematics & chemistry
      print(len(num3), num3)
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值