python - 字典和集合

python - 字典和集合

1.字典

1)增和改

字典[键] = 值 - 当键存在的时候是修改键对应的值;当键不存在的时候是添加键值对
字典.setdefault(键, 值) - 添加键值对(当键存在的时候不会修改原来的值)

cat = {'name': '美美', 'age': 2, 'color': '白色'}
print(cat)      # {'name': '美美', 'age': 2, 'color': '白色'}

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

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

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

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

练习:在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 stu in students:
    stu.setdefault('score', 0)
print(students)
# [{'name': 'stu1', 'tel': '1234', 'score': 89},
# {'name': 'stu2', 'tel': '465', 'score': 80},
# {'name': 'stu3', 'tel': '678', 'score': 0},
# {'name': 'stu3', 'score': 78},
# {'name': 'stu4', 'tel': '234', 'score': 0}]

2)删 - 删除键值对

del 字典[键] - 删除字典中指定键对应的键值对(如果键不存在会报错)
字典.pop(键) - 取出字典中指定键对应的值(如果键不存在会报错)

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

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

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

3)相关操作

字典不支持+、*,也不支持比较大小的运算符,只支持==、!=
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

4)相关函数

len(字典)
dict(数据) - 1) 数据本身是一个序列
2) 序列中的元素必须是有且只有两个元素的小序列
3) 小序列的第一个元素必须是不可变的数据

date = [('a', 10), ('b', 20)]
print(dict(date))       # {'a': 10, 'b': 20}

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

date3 = ('ab', 'cd', range(1, 3))
print(dict(date3))

# date4 = ('abc','cd',range(1, 3))    # 报错
# print(dict(date4))    # 报错

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

5)相关方法

字典.clear - 清空字典
字典.copy - 复制原字典产生一个一模一样的新字典
字典.update(序列) - 将序列中所有的元素都添加到字典中(如果本身就存在就会覆盖)。序列必须是字典或者能够转换成字典的序列

items、keys、values
字典.keys() - 获取字典所有的键,返回一个序列(这个序列不是列表或元组)

date3 = {'d': 100, 'e': 200}
print(dic2)     # {'a': 10, 'b': 20, 'c': 30}
dic2.update(date3)
print(dic2)     # {'a': 10, 'b': 20, 'c': 30, 'd': 100, 'e': 200}

dic2.update(['xy', 'mn'])
print(dic2)     # {'a': 10, 'b': 20, 'c': 30, 'd': 100, 'e': 200, 'x': 'y', 'm': 'n'}

dic2.update({'d': 1000, 'f': 2000})
print(dic2)     # {'a': 10, 'b': 20, 'c': 30, 'd': 1000, 'e': 200, 'x': 'y', 'm': 'n', 'f': 2000}

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)])

6)字典推导式

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

# 练习:通过字典的推导式交换一个字典的键和值
"""{'a': 10, 'b': 20}  -> {10:'a', 20:'b'}"""
dic3 = {'a': 10, 'b': 20, 'c': 30}
new_dic3 = {dic3[key]: key for key in dic3}
print(new_dic3)

2.集合

1)集合(set)

集合是容器:将{}作为容器标志,多个元素用逗号隔开:{元素1, 元素2, 元素3,…}
集合是可变的:支持增删改;集合是无序,不支持下标操作
元素:不可变的数据、元素是唯一的(具备自动去重的功能)

# 1)空集合
set1 = set()
print(type(set1), len(set1))    # <class 'set'> 0
# 2)集合是无序
print({1, 2, 3} == {3, 1, 2})   # True

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

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

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

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)     # {'c', 'b', 45, 78, 'a', 23, 89, 90}

# 3)删
"""
集合.remove(元素)       -   删除指定的元素,元素不存在会报错
集合.discard(元素)      -   删除指定的元素,元素不存在不会报错
"""
nums.remove(89)
print(nums)     # {'a', 45, 78, 'c', 'b', 23, 90}

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

# nums.remove(100)    # 报错
nums.discard(100)

# 4)改  -  集合无法直接修改元素的值,如果非要改就将要改的元素删除,添加新元素
nums.remove('a')
nums.add('A')
print(nums)

3)数学集合运算:

&(交集)、|(并集)、-(差集)、^(对称差集)、>/<(真子集)、>=/<=(子集)

nums1 = {1, 2, 3, 4, 5, 6, 7}
nums2 = {5, 6, 7, 8, 9}
# 1) 集合1 & 集合2   -   获取两个集合的公共元素(获取即在集合1又在集合2里面的元素)
print(nums1 & nums2)    # {5, 6, 7}

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

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

# 4)集合1 ^ 集合2   -   将两个集合合并,去掉中间公共部分
print(nums1 ^ nums2)    # {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

3.字符串

1)验证下标操作

(包括获取单个元素、切片、遍历)

# 1)获取单个元素
str1 = 'abcdef'
# 获取单个元素
print(str1[1])      # b
# 切片
print(str1[1:4])    # bcd
print(str1[1:5:2])  # bd
# 遍历
for x in str1:
    print(x)
# a
# b
# c
# d
# e
# f

2)相关操作:

+、*、比较运算、in 和 not in

str2 = 'abcde'
str3 = 'cdef'
str4 = 'abc'
str5 = 'acde'
print(str2 + str3)      # abcdecdef
print(str4 * 2)         # abcabc

str2 = 'abcde'
str3 = 'abd'
str4 = 'abc'
str5 = 'acde'
print(str2 > str4)      # True
print(str2 > str3)      # False
print(str2 == str4)     # False
print(str2 == str5)     # True

print(str3 in str2)     # False
print(str4 in str2)     # True
print(str5 in str2)     # False

print(str3 not in str2)     # True

3)len和str

print(len(str2))      # 5

a = [1, 2]
a = str(a)
print(a, type(a))   # [1, 2] <class 'str'>
print(a[0])         # [

4.作业:

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

    stu_info = [
        {'name': 'stu1', 'age': 18, 'score': 98, 'tel': '10000000898', 'gender': '男', },
        {'name': 'stu2', 'age': 19, 'score': 67, 'tel': '10000000891', 'gender': '女', },
        {'name': 'stu3', 'age': 20, 'score': 56, 'tel': '10000000892', 'gender': '男', },
        {'name': 'stu4', 'age': 16, 'score': 98, 'tel': '10000000893', 'gender': '不明', },
        {'name': 'stu5', 'age': 14, 'score': 44, 'tel': '10000000894', 'gender': '不明', },
        {'name': 'stu6', 'age': 21, 'score': 93, 'tel': '10000000895', 'gender': '女', }
    ]
    

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

    count = 0
    for stu in stu_info:
        if stu['score'] < 60:
            count += 1
    print('不及格学生的个数:', count)
    

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

    print('不及格学生的名字和对应的成绩:')
    for stu in stu_info:
        if stu['score'] < 60:
            print(stu['name'], stu['score'])
    

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

    print('手机尾号是8的学生的名字:')
    for stu in stu_info:
        if stu['tel'][-1] == '8':
            print(stu['name'])
    

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

    print('最高分和对应的学生的名字:')
    max_score = stu_info[0]['score']
    for stu in stu_info:
        stu_score = stu['score']
        if stu_score >= max_score:
            max_score = stu_score
            name_score = stu['name']
            print(max_score, name_score)
    

    5)删除性别不明的所有学生

    print('删除性别不明的所有学生')
    len1 = 0
    while len1 < len(stu_info) - 1:
        stu_gender = stu_info[len1]['gender']
        if stu_gender == '不明':
            del stu_info[len1]
        else:
            len1 += 1
    print(stu_info)
    

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

    print('将列表按学生成绩从大到小排序:')
    list1 = []
    while len(stu_info) != 0:
        for stu in stu_info:
            stu_score = stu['score']
            max_score = stu_info[0]['score']
            if stu_score >= max_score:
                max_score = stu_score
                list1.append(stu)
                stu_info.remove(stu)
    print(list1)
    
  2. 用三个集合表示三门学科的选课学生姓名(一个学生可以同时选多门课)

    math = {'stu1', 'stu2','stu3','stu4','stu5','stu9'}
    chinese = {'stu1', 'stu5','stu6', 'stu7'}
    english = {'stu3','stu4','stu5','stu8'}
    

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

    students = math | chinese | english
    print(len(students))
    

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

    only_math = math - chinese - english
    print('只选了第一个学科的人的数量:', len(only_math))
    for x in only_math:
        print(x)
    

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

    three_subject = math & chinese & english
    one_subject = math ^ chinese ^ english - three_subject
    print('只选了一门学科的学生的数量:', len(one_subject))
    for x in one_subject:
        print(x)
    

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

    two_subject = students - one_subject - three_subject
    print('选了两门学生的学生的数量:', len(two_subject))
    for x in two_subject:
        print(x)
    

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

    print('选了三门学生的学生的数量:', len(three_subject))
    for x in three_subject:
        print(x)
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值