Day7-元组和字典

元组和字典及相关操作

01.元组就是不可变的列表

# 元组可以是任何类型的数据
tuple1 = (10, 20, 30, 'a', True, 1 + 3)

# 列表获取元素的方法都是用于元组
tuple2 = ('杨幂', '刘亦菲', '赵丽颖', '张艺馨', '孙俪')

# 获取单个元素
print(tuple2[1])
print(tuple2[-1])

# 遍历
for x in tuple2:
    print('x', x)

for index, item in enumerate(tuple2):
    print(index, item)

# 切片
print(tuple2[::-1])

# 3)列表相关操作都适用于元组
print((1, 2, 3) + ('a', 'b'))  # (1, 2, 3, 'a', 'b')
print((1, 2, 3) * 3)  # (1, 2, 3, 1, 2, 3, 1, 2, 3)
print((1, 2, 3) == (1, 3, 2))  # False
print((1, 2, 3) == (1, 2, 3))  # True
print((100, 200, 300) > (100, 1000)) # False
print(100 in (100, 200, 300))  # True
nums = (10, 54, 56, 27)
print(max(nums))  # 56
print(sorted(nums))  # [10, 27, 54, 56]
print(tuple('abc'))  # ('a', 'b', 'c')

# 相关方法
nums = (10, 54, 56, 27, 10, 30)
print(nums.count(10))  # 2
print(nums.index(54))  # 1
  1. 元组特有的一些方法和功能

    1. 只有一个元素的元组:()中唯一的元素后需要加一个逗号

      list1 = [100]  # <class 'list'>
      tuple1 = (100)
      print(type(tuple1))  # <class 'int'>
      tuple1 = (100, )
      print(type(tuple1))  # <class 'tuple'>
      
    2. 直接多个数据用逗号隔开表示的也是一个元组(元组的括号在没有歧义的时候可以省略)

      tuple2 = 100, 200, 300
      print(type(tuple2), tuple2)  # <class 'tuple'> (100, 200, 300)
      tuple3 = (100, 200, 300) + (20, 30)
      
    3. 获取元素的时候可以通过让变量的个数和元组中元素的个数保持一致,来分别获取元组中每个元素的值

      point = (100, 200, 300)
      x, y, z = point
      print(x, y, z)  # 100 200 300
      a, b, c = 10, 20, 30  # a, b, c =(10, 20, 30)
      
    4. 让变量个数少于元组中元素的个数,并且在一个元素前加*,先让没有 * 的变量依次获取元素,然后把剩下的元素作为一个列表返回

      stu = ('小明', 30, '男', 89, 70, 56, 100)
      name, age, gender, *scores = stu  # 没有星号的变量每个对应元组中的变量,带星号的对应剩下的变量(星号只能有一个)
      print(name, age, gender)  # 小明 30 男
      print(scores)  # [89, 70, 56, 100]
      
      a, *b = stu
      print(a)  # 小明
      print(b)  # [30, '男', 89, 70, 56, 100]
      
      a, *b, c = stu
      print(a, c)  # 小明 100
      print(b)  # [30, '男', 89, 70, 56]
      
      a, *b, c, d = stu
      print(a, c, d)
      

02.字典

用字典的原因:用列表同时保存多个意义不同的数据的时候,代码的可读性很低。字典可以保存多个意义不同的数据

  1. 什么是字典:字典是容器型的数据类型,将大括号{}作为容器的标志,里面多个元素用逗号隔开(其中元素必须是键值对):{键1:值1,键2:值2,键3:值3,…}

    1. 字典可变(支持增删改); 字典是无序(不支持下标操作)
    2. 字典的元素:键是不可变的,唯一的;值可以是任何类型的数据,并且可以重复
    print({'a': 10, 'b': 20} == {'b': 20, 'a': 10})  # True
    dict1 = {
        10: 100,
        'abc': 200,
        (10,): 300
    }
    
    # dict2 = {[10, 20]: 100}  # TypeError: unhashable type: 'list'
    # 练习:定义一个字典,保存一条狗的信息,包括:名字,品种,颜色,年龄
    dog = {'name': 'kk', 'breed': 'huskie', 'color': 'white', 'age': 3}
    print(dog['name'])
    
  2. 元素的增删改查

    1. 查 - 获取字典的值

      获取单个值:

      1. 字典[key] - 获取字典中指定key对应的值(如果key不存在,会报错)
      2. 字典.get(key) - 获取字典中指定key对应的值(如果key不存在,不会报错,返回None)
      3. 字典.get(key, 默认值) - 获取字典中指定key对应的值(如果key不存在,不会报错,返回默认值)
      movie1 = {
          'name': '战狼',
          'director': '吴京',
          'actor': '吴京',
          'year_of_release': '2015',
          'genre': '动作'
      }
      
      movie2 = {
          'name': '沉默的羔羊',
          'director': '乔纳森',
          'actor': '朱迪佛斯特',
          'year_of_release': '1991',
          'genre': '惊悚'
      }
      print(movie1['name'])
      print(movie1['genre'])
      print(movie2.get('genre'))  # 惊悚
      print(movie2.get('hi'))  # None
      
      print(movie2.get('year_of_release', '321'))  # 1991
      print(movie2.get('score', 1))  # 1
      

    遍历字典

    (推荐使用)方法一:

    for 变量 in 字典:

    ​ 循环体(变量在循环体中得到的是key)

    print('======')
    for x in movie1:
        print(x, movie1[x])
    

​ 方法二:

​ for key, value in 字典.item():

​ 循环体(循环体中变量1取到的所有的键,变量2取到的是所有键对应的值)

print('======')
print(movie1.items())
for x, y in movie1.items():
    print(x, y)

  1. 增/改 - 添加键值对/修改键值对的值

    1. 字典[key] = 值 - 当key不存在,就是添加键对;当key存在时就是修改key对应的值
    subject = {
        'name': 'python',
        'score': 3,
        'class_hour': 20,
        'direction': ['数据分析', 'web后端', '爬虫', '自动测试', '自动化运维']
    }
    print(subject)
    subject['teacher'] = '余婷'
    print(subject)
    
    subject['score'] = 4
    
  2. """
    del 字典[key] - 删除字典指定key对应的键值对
    字典.pop(key) - 取出字典中指定key对应的值
    """
    del subject['class_hour']
    print(subject)
    
    del_item = subject.pop('direction')
    print(subject)
    
字典的应用
# 练习:
# 1.定义一个变量同时保存多条狗的信息,每条狗有:名字,年龄,性别,品种,价格和颜色
# 2. 统计5条狗中公的有多少条
# 3. 打印所有价格超过2000元的狗的名字

dog1 = {
    'name': 'heihei',
    'age': 3,
    'sex': 'boy',
    'breed': 'huskie',
    'price': 2500,
    'color': 'green'
}
dog2 = {
    'name': 'IU',
    'age': 2,
    'sex': 'girl',
    'breed': 'chiwawa',
    'price': 1500,
    'color': 'black'
}
dog3 = {
    'name': '马飞飞',
    'age': 4,
    'sex': 'boy',
    'breed': '土狗',
    'price': 10,
    'color': 'yellow'
}
dog4 = {
    'name': '马哥',
    'age': 1,
    'sex': 'boy',
    'breed': '上流',
    'price': 3000,
    'color': 'yellow'
}
num_of_boys = 0
dogs = [dog1, dog2, dog3, dog4]
for dic in dogs:
    if dic.get('sex') == 'boy':
        num_of_boys += 1
    if dic.get('price') > 2000:
        print(dic.get('name'))
print(num_of_boys)

# 定义一个变量保存一个班级信息
c = {
    'name': 'python2003',
    'position': '23教室',
    'lecturer': {
        'name': '余婷',
        'sex': '女',
        'age': 18,
        'qq': '726559022'
    },
    'class_teacher': {
        'name': '杨云珂',
        'sex': '女',
        'age': 20,
        'qq': '7128313'
    },
    'students': [
        {'name': '马杰', 'id': '6272636716212', 'tel': '110'},
        {'name': '佳伟', 'id': '7823823', 'tel': '110'},
        {'name': '朝林', 'id': '79283293', 'tel': '110'},
        {'name': '马杰', 'id': '6272636716212', 'tel': '110'},
        {'name': '马杰', 'id': '6272636716212', 'tel': '110'}
    ]


}

print(c)
字典的相关操作和方法
  1. 相关操作

    1. 字典不支持加法,乘法和比较大小的运算

    2. 判断是否相等

      print({'a': 10, 'b': 20} == {'b': 20, 'a': 10})  # True
      

    Is - 判断两个数据的地址是否相等

    a = {'a': 10}
    b = {'a': 10}
    c = a
    print(a == b)  # True
    print(a is b)  # False
    print(a is c)  # True
    
  2. In and not in

    Key in 字典 - 判断字典中是否有指定的key

    dict1 = {'a': 10, 'b': 20, 'c': 30}
    print(10 in dict1)  # False
    print('b' in dict1)  # True
    
    1. 相关函数:len/dict

      1. len(字典) - 获取字典中键值对的个数
     ```python
     print(len(dict1))  # 3
     ```
    
       2. dict(数据) - 将其他数据转换成字典(数据的要求:1.序列 2.序列中的元素还是序列 3. 内部的序列有且只有两个元素,第一个元素不可变)
    
     ```python
     list1 = ['ab', (1, 2), [3, 4]]
     print(dict(list1))
     ```
    

​ 将字典转换成其他数据

stu = {'name': '小明', 'age': 18, 'score': 100}
# 1) 将字典转换成列表/元组 - 将key作为列表/元组的元素
print(list(stu))  # ['name', 'age', 'score']
print(tuple(stu))  # ['name', 'age', 'score']

# 2)将字典转换成字符串
print(str(stu))  # "{'name': '小明', 'age': 18, 'score': 100}"

# 3)将字典转换成布尔
print(bool({}))  # False
print(bool(stu))  # True
  1. 相关方法

    stu = {'name': '小明', 'age': 18, 'score': 100}
    stu.clear()
    print(stu)  # {}
    
    # 2)字典.copy()
    stu = {'name': '小明', 'age': 18, 'score': 100}
    stu1 = stu
    stu['name'] = '小花'
    print(stu1)  # {'name': '小花', 'age': 18, 'score': 100}
    
    stu = {'name': '小明', 'age': 18, 'score': 100}
    stu2 = stu.copy()
    print(stu2)  # {'name': '小明', 'age': 18, 'score': 100}
    stu['name'] = '小花'
    print(stu2)  # {'name': '小明', 'age': 18, 'score': 100}
    
    # 3) dict.fromkeys(序列,默认值 = None) - 创建一个新的字典,序列中所有的元素会作为新字典的key, 默认值是所有key对应的值
    new_dict = dict.fromkeys('abc')
    print(new_dict)  # {'a': None, 'b': None, 'c': None}
    
    new_dict = dict.fromkeys(['name', 'age', 'sex'], ['张三', 19, '男'])
    
    print(new_dict)  # {'name': ['张三', 19, '男'], 'age': ['张三', 19, '男'], 'sex': ['张三', 19, '男']}
    
    # 4) 字典.items(), 字典.keys(), 字典.values()
    stu = {'name': '小明', 'age': 18, 'score': 100}
    print(stu.items())  # dict_items([('name', '小明'), ('age', 18), ('score', 100)])
    print(stu.keys())  # dict_keys(['name', 'age', 'score'])
    print(stu.values())  # dict_values(['小明', 18, 100])
    
    # 5) 字典.setdefault(key, value) - 在字典中添加键值对
    # 如果键值对已存在,setdefault不会替换它。单纯的添加不会修改
    stu.setdefault('weight', 100)
    print(stu)
    
    # 6)字典1.update(字典2)  - 将字典2中所有的键值对全部添加到字典1中
    stu.update({'a': 10, 'b': 20})
    print(stu)  # {'name': '小明', 'age': 18, 'score': 100, 'weight': 100, 'a': 10, 'b': 20}
    
    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
我能为您提供Python语言的实现代码,但是我无法上传文件或代码片段,请您理解。 以下是代码实现: 1. 列表 ```python def day_of_year_list(date): days_month = [31,28,31,30,31,30,31,31,30,31,30,31] year, month, day = date.split('-') year, month, day = int(year), int(month), int(day) if (year%4==0 and year%100!=0) or year%400==0: days_month[1] = 29 days_count = sum(days_month[:month-1]) + day return days_count ``` 2. 元组 ```python def day_of_year_tuple(date): days_month = (31,28,31,30,31,30,31,31,30,31,30,31) year, month, day = date.split('-') year, month, day = int(year), int(month), int(day) if (year%4==0 and year%100!=0) or year%400==0: days_month = (31,29,31,30,31,30,31,31,30,31,30,31) days_count = sum(days_month[:month-1]) + day return days_count ``` 3. 集合 ```python def day_of_year_set(date): days_month = {1:31,2:28,3:31,4:30,5:31,6:30, 7:31,8:31,9:30,10:31,11:30,12:31} year, month, day = date.split('-') year, month, day = int(year), int(month), int(day) if (year%4==0 and year%100!=0) or year%400==0: days_month[2] = 29 days_count = sum([days_month[i] for i in range(1, month)]) + day return days_count ``` 4. 字典 ```python def day_of_year_dict(date): days_month = {'January':31, 'February':28, 'March':31, 'April':30, 'May':31, 'June':30, 'July':31, 'August':31, 'September':30, 'October':31, 'November':30, 'December':31} year, month, day = date.split('-') year, day = int(year), int(day) if (year%4==0 and year%100!=0) or year%400==0: days_month['February'] = 29 days_count = sum([days_month[key] for key in days_month.keys() if key!=month]) + day return days_count ``` 以上是针对不同数据类型的实现,您可以根据需要选择其中一种来使用。具体调用方法如下: ```python date = '2022-02-08' days_count_list = day_of_year_list(date) # 使用列表实现的方法 days_count_tuple = day_of_year_tuple(date) # 使用元组实现的方法 days_count_set = day_of_year_set(date) # 使用集合实现的方法 days_count_dict = day_of_year_dict(date) # 使用字典实现的方法 print(f"使用列表实现的方法计算结果为:{days_count_list}") print(f"使用元组实现的方法计算结果为:{days_count_tuple}") print(f"使用集合实现的方法计算结果为:{days_count_set}") print(f"使用字典实现的方法计算结果为:{days_count_dict}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值