day7-字典与元组

day7-字典与元组
1.元组

1.什么是元组(tuple)

"""
元组是容器型数据类型(序列),将()作为容器的标志,里面多个元素之间用逗号隔开:(元素1, 元素2, 元素3,...)
元组是不可变的(说明不支持增删改);元组是有序的(说明支持下标操作)
元素的要求:任何类型的数据
"""
t1 = (10, 20, 30)
print(t1, type(t1))   # (10, 20, 30) <class 'tuple'>

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

​ 列表中除了和增删改相关操作以外的操作元组都支持

​ 例如:查、相关操作、相关方法(除了增删改相关的)、相关函数

tuple1 = (10, 23, 78, 9)
print(tuple1[-1])   # 9
print(tuple1[1:])   # (23, 78, 9)
tuple1 = (10, 23, 78, 9)
for x in tuple1:
    print(x, end=' ')   # 10 23 78 9
tuple1 = (10, 23, 78, 9)
for index in range(len(tuple1)):
    print(tuple1[index], end=' ')  # 10 23 78 9
t2 = (10, 23, 10, 45, 9, 12, 10)
print(t2.count(10))   # 3
print(t2.index(23))   # 1
print(max(t2), min(t2))  # 45 9
print(sum(t2))   # 119
# sorted排序不管对何种序列排序,最终都将产生一个新的列表
print(sorted(t2))   # [9, 10, 10, 10, 12, 23, 45]
print(tuple('abc'))  # ('a', 'b', 'c')
print(len(t2))  # 7

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

3.元组特殊或者常用操作

​ 1)只有一个元素的元组

t1 = (10,)
print(t1, type(t1))  # (10,) <class 'tuple'>

​ 2)元组在没有歧义的情况下可以省略小括号(),直接用逗号将多个数据隔开,表示的也是一个元组

t3 = 10, 20, 30, 40
print(t3, type(t3))  # (10, 20, 30, 40) <class 'tuple'>
t3 = 34, 56, 78*2
print(t3)  # (34, 56, 156)
t4 = t3*2
print(t4)  # (34, 56, 156, 34, 56, 156)

​ 3)同时使用多个变量获取元组的元素(列表也支持)

t3 = ('小明', 18, 90)
print(t3[0])  # 小明
# a.让变量的个数和元组中元素的个数保持一致
t3 = ('小明', 18, 90)
name, age, scores = t3
print(name, age, scores)
# b.让变量的个数小于元组元素的个数,但是必须在某一个变量前加*
# 先让不带*的变量按照位置获取元素,剩下的部分全部保存到带*的变量对应的列表中
t3 = ('小明', 18, 170, 90, 80, 78, 76)
name, age, height, weight, *scores = t3
print(name, age, height, weight, scores)  # 小明 18 170 90 [80, 78, 76]
2.字典

1.什么是字典

​ 1)字典是容器行型数据类型(序列),将{}作为容器标志,里面多个键值对用逗号隔开:{键1:值1, 键2:值2, 键3:值3, … …}

​ 2)字典作为容器的特征:字典是可变的(支持增删改操作);字典是无序的(不支持下标操作)

​ 3)元素 - 键值对

​ 键 :必须是不可变的数据,例如:元组,数字,字符串。键是唯一的

​ 值(才是真正想要保存的数据):没有要求

print({'a':10, 'b': 20} == {'b': 20,  'a': 10})  # True
# 因为字典是无序的,只要里面的键值对一样,不管顺序如何变化,都是相等的
# 1)空字典
dict1 = {}
print(dict1, type(dict1))  # {} <class 'dict'>

# 2)键必须是不可变的数据类型
dict2 = {'a': 10, 1: 20, (1, 2): 30}
print(dict2)   # {'a': 10, 1: 20, (1, 2): 30}
# dict3 = {'a': 10, 1: 20, [1, 2]: 30}
# print(dict3)  # 报错!

# 3)键是唯一的
dict4 = {'a': 10, 1: 20, 'a': 30}
print(dict4) # {'a': 30, 1: 20}
dict5 = {'a': 10, 'b': 20, 12: 12, True: False}
print(dict5)  # {'a': 10, 'b': 20, 12: 12, True: False}

2.字典的查操作是获取字典的值

# 1.查单个
"""
1)字典[键] - 获取字典中指定键对应的值;当键不存在的时候会报错
2)字典.get(键) == 字典.get(键, None) - 获取字典中指定键对应的值;当键不存在的时候不会报错,返回None
3)字典.get(键,默认值) - 获取字典中指定键对应的值;当键不存在的时候不会报错,返回默认值
"""
dog = {'name': '旺财', 'breed': '中华田园犬', 'age': 3, 'color': '黄色'}
print(dog['name'])  # 旺财
print(dog.get('name'))  # 旺财
print(dog.get('gender', '男')) # 男
# 2.遍历
"""
for 变量 in 字典:
	循环体
变量取到的是键
"""
dog = {'name': '旺财', 'breed': '中华田园犬', 'age': 3, 'color': '黄色'}
for x in dog:
    print(x, dog[x])
# 用一个字典保存一个班级的信息
class1 = {
    'name': 'Python2106',
    'address': '9教',
    'lecturer': {
        'name': '余婷',
        'age': 18,
        'tel': '13678192302',
        'QQ': '726550822'
    },
    'head_teacher': {
        'name': '张瑞燕',
        'tel': '110',
        'QQ': '7283211'
    },
    'students': [
        {
            'name': '陈来',
            'age': 20,
            'gender': '女',
            'score': 98,
            'contacts': {
                'name': 'p2',
                'tel': '120'
            }
        },
        {
            'name': '葛奕磊',
            'age': 25,
            'gender': '男',
            'score': 80,
            'contacts': {
                'name': 'p1',
                'tel': '119'
            }
        }
    ]
}
# 根据上述班级字典完成以下操作
# 1. 获取班级的名字
print(class1['name'])
print(class1.get('name'))
# 2. 获取讲师的名字和年龄
print(class1['lecturer']['name'])
print(class1.get('lecturer').get('name'))
print(class1['lecturer']['age'])
# 3. 获取班主任的名字和电话
print(class1['head_teacher']['name'])
print(class1.get('head_teacher').get('name'))
print(class1['head_teacher']['tel'])
# 4. 获取第一个学生的姓名
print(class1['students'][0]['name'])
print(class1.get('students')[0].get('name'))
# 5. 获取所有学生的联系人的名字
student1 = class1['students']
for x in student1:
    print(x['contacts']['name'])
# 6. 计算所有学生的平均分
sum1 = 0
for x in student1:
    sum1 += x['score']
result = sum1 / len(student1)
print('学生的平均分:', result)

3.字典的增删改

# 1.增 - 添加键值对
# 2.改 - 修改键对应的值
# 语法: 字典['键'] = 值 -  当键存在的时候是修改,键不存在就是添加
goods = {'name': '泡面', 'price': 3.5, 'count': 10}
print(goods)
goods['price'] = 4
print(goods)  # {'name': '泡面', 'price': 4, 'count': 10}
goods['place'] = '山东'  # {'name': '泡面', 'price': 4, 'count': 10, 'place': '山东'}
# 3.删
# 1)del 字典[键]  - 删除字典中指定键对应的键值对
goods = {'name': '泡面', 'price': 3.5, 'count': 10}
del goods['price']
print(goods)  # {'name': '泡面', 'count': 10}

# 2)字典.pop(键) - 取出字典中指定键对应的值
goods = {'name': '泡面', 'price': 3.5, 'count': 10}
result = goods.pop('price')
print(goods)  # {'name': '泡面', 'count': 10}
print(result) # 3.5

3.5, ‘count’: 10}
del goods[‘price’]
print(goods) # {‘name’: ‘泡面’, ‘count’: 10}

2)字典.pop(键) - 取出字典中指定键对应的值

goods = {'name': '泡面', 'price': 3.5, 'count': 10}
result = goods.pop('price')
print(goods)  # {'name': '泡面', 'count': 10}
print(result) # 3.5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值