10.元组&字典&集合

一、元组

1.概念

和列表相似,本质上是一种有序的集合

元组和列表的不同之处:

​ a.列表:[] 元组:()

​ b.列表中的元素可以进行增加和删除操作,但是,元组中的元素不能修改【元素:一旦被初始化,将不能发生改变】

2.元组基本操作

创建列表:

​ 创建空列表:list1 = []

​ 创建有元素的列表:list1 = [元素1,元素2,。。。。。]

创建元组

​ 创建空元组:tuple1 = ()

​ 创建有的元组:tuple1 = (元素1,元素2,。。。。)

# 1.概念
"""
列表:是一种有序的,可变的,可以存储重复元素的,可以存储不同类型数据的集合
元组:是一种有序的,不可变的,可以存储重复元素的,可以存储不同类型数据的集合
​
元组和列表的不同之处:
    a.数据类型的表示形式不同:列表:[]     元组:()
    b.列表中的元素可以进行增加和删除操作,但是,元组中的元素不能修改【元素:一旦被初始化,将不能发生改变】
"""
​
# 2.定义
# 元组:tuple    列表:list
# a.命名格式:尽量不要直接使用tuple或list
list1 = [34,5,6,6,6,6,6,"abc"]
print(list1,type(list1))
tuple1 = (34,6,7,7,7,7,7,"abc")
print(tuple1,type(tuple1))
​
# b.当元组中只有一个元素时,则需要在元素的后面添加逗号,以消除歧义
list2 = [45]
print(list2,type(list2))
tuple2 = (45,)
print(tuple2,type(tuple2))
​
# c.列表是可变的,元组是不可变的
list1[1] = 100
print(list1)
# tuple1[1] = 100   # TypeError: 'tuple' object does not support item assignment
​
# 【面试题】
t1 = (34,4,5,[45,5,78])
t1[-1][0] = 100
print(t1)  # (34, 4, 5, [100, 5, 78])
​
# 3.操作
# a.+
t1 = (1,2)
t2 = (3,4)
print(t1 + t2)
​
# b.*
print(t1 * 3)
​
# c.in和not in
print(2 in t1)
print(23 not in t1)
​
# d.切片
t1 = (11,22,33,44,55,66,77,88,99)
print(t1[100:])   # ()
print(t1[0:-1])   # (11.....88)
​
print(t1[1:5:-1])  # ()
print(t1[-1:-5:-1]) # (99,88....66)
​
print(t1[-5:-1:-1])  # ()
print(t1[3::-1])     # (44...11)
​
# 4.遍历
for ele in t1:
 print(ele)
​
for i in range(len(t1)):
 print(t1[i])
​
for i,num in enumerate(t1):
 print(i,num)
​
# 5.系统功能
# a.
print(len(t1))
​
# b
i = t1.index(22)
​
​
# c.
c = t1.count(22)
​
# d.
print(max(t1))
print(min(t1))
​
# e.list()和tuple()
l1 = [34,6]
print(l1,type(l1))
​
t1 = tuple(l1)
print(t1,type(t1))
​
l2 = list(t1)
print(l2,type(l2))

二、字典

1.概念

列表和元组的使用缺点:当存储的数据要动态添加、删除的时候,我们一般使用列表,但是列表有时会遇到一些麻烦,缺点:定位元素比较麻烦

# 一个列表保存5个学生的成绩,
score_list = [66,100,70,78,99]
score_tuple = (66,100,70,78,99)

解决方案:既能存储多个数据,还能在访问元素的很方便的定位到需要的元素,采用字典

# 一个字典保存5个学生的成绩,
score_dict = {"小明":66,"小花":100,"jack":70,"tom":70,"bob":99}

习惯使用场景【不是绝对的】:

  • 列表更适合保存相似数据,比如多个商品、多个姓名、多个时间

  • 字典更适合保存不同数据,比如一个商品的不同信息、一个人的不同信息 或者 需要定位数据

2.定义字典

语法:{键1:值1, 键2:值2, 键3:值3, ..., 键n:值n}

说明:

  • 字典和列表类似,都可以用来存储多个数据

  • 在列表中查找某个元素时,是根据下标进行的;字典中找某个元素时,是根据键查找的(就是冒号:前面的那个值,例如上面代码中的'name'、'id'、'sex')

  • 字典中的每个元素都由2部分组成,键:值。例如 'name':'班长' ,'name'为键,'班长'为值

  • 键只能使用数字、布尔值、元组,字符串等不可变数据类型,但是一般习惯使用字符串,切记不能使用列表等可变数据类型,但是,值的数据类型没有限制

  • 每个字典里的key都是唯一的,如果出现了多个相同的key,后面的value会覆盖之前的value

# 【面试题】列举至少3种定义字典的方式
​
# 1.                *****
dict1 = {'name':'张三','age':18}
print(dict1)
​
# 2.                *****
dict2 = {}
dict2['aaa'] = 10
dict2['bbb'] = 20
print(dict2)
​
# 3.dict(key1=value1,key2=value2.....)
dict3 = dict(x=23,y=56,z=10)
print(dict3)
​
dict31 = {10:0,20:1,30:2}
print(dict31)
# 注意:使用dict(key1=value1...)定义的字典,key只能是字符串
# dict32 = dict(10=0,20=1,30=2)
​
# 4.dict([(key1,value1),(key2,value2)......])
# 列表是可变的,元组是不可变的
dict4 = dict([('abc',100),('hello',200)])
print(dict4)
# 注意:下面三种写法可以使用,但是不规范
# dict4 = dict([['abc',100],['hello',200]])
# print(dict4)
# dict4 = dict((('abc',100),('hello',200)))
# print(dict4)
# dict4 = dict((['abc',100],['hello',200]))
# print(dict4)
​
# 5.dict(zip([key1,key2.....],[value1,value2.....]))                 *******
dict5 = dict(zip(['zhangsan','jack','tom'],[12,20,15]))
print(dict5)
dict5 = dict(zip(('zhangsan','jack','tom'),(12,20,15)))
print(dict5)
dict5 = dict(zip(['zhangsan','jack','tom','bob'],[12,20,15]))
print(dict5)
dict5 = dict(zip(['zhangsan','jack','tom'],[12,20,15,30]))
print(dict5)

3.字典的基本使用

# 1.{}
l1 = [34,5,6]
print(l1,type(l1))
t1 = (34,5,6)
print(t1,type(t1))
d1 = {'a':10,'b':20}
print(d1,type(d1))
s1 = {34,6,67,7,7}    # 集合:无序,去重
print(s1,type(s1))
​
# 注意:字典和集合都是使用{}表示的,但是空{}默认表示字典
a = {}          # 空字典
print(a,type(a))
b = []          # 空列表
print(b,type(b))
c = ()          # 空元组
print(c,type(c))
d = set()       # 空集合
print(d,type(d))
​
# 2.字典中键值的注意事项
# a.字典中的键只能是不可变的数据类型,常用字符串
"""
不可变的数据类型:int  float  bool str  tuple
可变的数据类型:list  dict  set
"""
dict1 = {10:23,45.4:10,True:100,'abc':45,(1,2):56}
print(dict1)
# dict1 = {10:23,45.4:10,True:100,'abc':45,(1,2):56,[3,4]:34}
# print(dict1)
​
# b.字典中的值可以是任意的数据类型
dict2 = {1:10,2:34.5,3:False,4:'abc',5:[34,56],6:(345,6)}
print(dict2)
​
# c.字典中的键是唯一的,值可以重复
# 注意:字典的所有的键相当于一个集合【集合不允许存储重复元素】
#  字典的所有的值相当于一个列表【列表允许存储重复元素】
​
# 如果一个字典中出现了多个相同的key,后面的value会覆盖之前的value
dict3 = {'name':'赵四','age':18,'name':'jack'}
print(dict3)
​
dict3 = {"小明":66,"小花":100,"jack":70,"tom":70,"bob":99}
print(dict3)

4.字典中键值的访问

"""
注意:
    a.字典中的键相当于列表中的索引,列表中通过索引访问元素,字典中通过键访问对应的值
    b.字典是可变的数据类型,可以通过键将原值获取出来,然后进行修改
"""
​
# 1.通过键获取值
# a.语法一:字典[键],注意:键一定要存在,才能获取到对应的值
info_dict = {'name':'jack','age':10,"gender":'male'}
age = info_dict['age']
print(age)
​
# 注意:如果访问一个不存在的key,则报错KeyError: 'hobby'
# hobby = info_dict['hobby']
# print(hobby)
# 优化
key = 'hobby'
if key in info_dict:
    hobby = info_dict['hobby']
    print(hobby)
else:
    print(f"{key}不存在")
​
# b.语法二:字典.get(key,default),如果键存在,则获取对应的值;      ******
# 1>default省略,如果键不存在,默认获取到的None
print(info_dict.get('age'))
print(info_dict.get('hobby'))
​
# 2>【了解】default不省略,如果键不存在,获取到的default
print(info_dict.get('age',66))
print(info_dict.get('hobby','dance'))
​
# 2.通过键修改值
# 注意:字典是可变的数据类型,其中的值可以随时被修改,但是键不能被修改
info_dict = {'name':'jack','age':10,"gender":'male'}
print(info_dict)
# a.如果键存在,字典[键] = 值,表示修改指定键对应的值
info_dict['name'] = 'hello'
print(info_dict)
# b.如果键不存在,字典[键] = 值,表示将指定的键值对添加到字典中     ******
info_dict['score'] = 100
print(info_dict)

5.遍历字典

info_dict = {'name':'jack','age':10,"gender":'male'}
​
# 1.获取key               ******
for key in info_dict:
    print(key,info_dict[key])
​
# 2.获取key
# print(info_dict.keys())  # 获取字典中所有的键
for key in info_dict.keys():
    print(key,info_dict[key])
​
# 3.获取value
print(info_dict.values())   # 获取字典中所有的值
for value in info_dict.values():
    print(value)
​
"""
注意:
    a.通过key获取value,语法:字典[key]
    b.通过value获取key,无法直接获取,只能通过循环遍历
    c.在字典中,通过key获取到的value是唯一的,但是,通过value获取到的key不一定唯一
"""
​
# 4.获取key和value                 *******
# print(info_dict.items())     # 获取字典中的键值对
for key,value in info_dict.items():
    print(key,value)
​
# a,b = (23,5)    # 拆包
# print(a,b)

6.字典使用练习

# 1.统计一个列表中每个元素出现的次数
list1 = [34,45,56,57,7,7,45,45,7,7,7]
# 方式一:
dict1 = {}  # key:元素  value:元素出现的次数
for ele in list1:
    if ele not in dict1:
        dict1[ele] = 1    # 不存在,添加键值对
    else:
        dict1[ele] += 1   # 存在,修改指定键对应的值
print(dict1)
​
# 方式二
dict2 = {}
for ele in list1:
    if ele not in dict2:
        dict2[ele] = list1.count(ele)
print(dict2)
​
# 2.统计一个列表中出现次数最多的元素
# a.统计列表中每个元素出现的次数
dict2 = {}
for ele in list1:
    if ele not in dict2:
        dict2[ele] = list1.count(ele)
print(dict2)
# b.获取dict2中value的最大值
max_value = max(dict2.values())
print(max_value)
# c.在dict2中通过value获取key
keylist = []
for key,value in dict2.items():
    if value == max_value:
        keylist.append(key)
print(f"出现次数最多的元素是:{keylist},对应的次数为:{max_value}")
​
# 3.已知list1 = ['a','b','c'],list2 = [34,56,8]
# 以list1中的元素作为key,list2中的元素作为value,生成一个字典
list1 = ['a','b','c']
list2 = [34,56,8]
dict2 = dict(zip(list1,list2))
print(dict2)
​
# 4.已知下面的列表,获取所有学生的成绩
stulist = [
    {'name':'zhangsan','age':10,"score":90},
    {'name':'lisi','age':11,"score":70},
    {'name':'xiaoming','age':12,"score":99},
    {'name':'xiaohua','age':9,"score":66}
]
# 说明:不管列表,元组,字典等数据类型如何嵌套,进行拆分处理
# 方式一
scorelist = []
for studict in stulist:
    scorelist.append(studict['score'])
print(scorelist)
​
# 方式二
scorelist = [studict['score'] for studict in stulist]
print(scorelist)

7.字典推导式

"""
列表推导式:[元素的规律  for循环   if语句]
字典推导式:{key:value for循环  if语句}
"""
# 1.【面试题】已知一个字典{'a':10,'b':20},实现程序,交换key和value,生成一个新的字典
dict1 = {'a':10,'b':20}
# 方式一
dict2 = {}
for key,value in dict1.items():
    dict2[value] = key
print(dict2)
​
# 方式二
dict2 = dict(zip(dict1.values(),dict1.keys()))
print(dict2)
​
# 方式三
dict2 = {value:key for key,value in dict1.items()}
print(dict2)
​
# 2.生成一个字典{1:1,3:9,5:25,7:49,9:81}
# 方式一
dict21 = {n:n ** 2 for n in range(1,10,2)}
print(dict21)
​
# 方式二
dict22 = {n:n ** 2 for n in range(1,10) if n % 2 == 1}
print(dict22)
​
# 3.【面试题】
list3 = [m + n for m in 'abc' for n in '123']
print(list3)  # 9  ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
dict3 = {m:n for m in 'abc' for n in '123'}
print(dict3)  # 3  {'a': '3', 'b': '3', 'c': '3'}

8.字典系统功能

# 一、增
dict1 = {'a':10,'b':20}
print(dict1)
​
# 1.字典[key] = value,当key不存在时,表示增加键值对     *****
# dict1['c'] = 30
# print(dict1)
​
# 2.update():更新,合并字典,将指定字典中的键值对添加到原字典中     ******主要会出现在面试题中
# dict1.update(dict2):将dict2中的键值对添加到dict1中
new_dict = {'x':34,'y':75}
dict1.update(new_dict)
print(dict1)
print(new_dict)
​
# 3.setdefault(key,default):通过设置默认值的方式增加键值对,了解
dict1 = {'a':10,'b':20}
print(dict1)
# a.default省略,则向指定字典中添加:key:None
dict1.setdefault('abc')
print(dict1)  # {'a': 10, 'b': 20, 'abc': None}
​
# b.default未省略,则向指定字典中添加:key:default
dict1.setdefault('xyz',88)
print(dict1)  # {'a': 10, 'b': 20, 'abc': None, 'xyz': 88}
​
​
# 二、删
# 1.pop(key):弹出,删除指定key对应的键值对,     ********
# 【实际工作原理:将指定键值对从字典中移除,但是在内存中】
dict1 = {'name':"张三",'age':18,'hobby':"篮球"}
print(dict1)
r = dict1.pop('age')   # pop跟列表中的用法类似,返回被删除的数据
print(dict1)
print(r)
​
# 2.popitem():在Python3.7之前,表示随机删除一对,在3.7之后,删除最后一对
dict1 = {'name':"张三",'age':18,'hobby':"篮球"}
print(dict1)
dict1.popitem()
print(dict1)
​
# 3.clear()
dict1 = {'name':"张三",'age':18,'hobby':"篮球"}
print(dict1)
dict1.clear()
print(dict1)
​
# 4.del
dict1 = {'name':"张三",'age':18,'hobby':"篮球"}
print(dict1)
del dict1['age']
print(dict1)
​
# del dict1     # 删除字典
​
# 三、改
dict1 = {'name':"张三",'age':18,'hobby':"篮球"}
print(dict1)
dict1['age'] = 66
print(dict1)
​
# 四、查
print(len(dict1))  # 获取键值对的对数
print(dict1.keys())
print(dict1.values())
print(dict1.items())
​
# 五、其他
# 但凡是可变的数据类型,都有copy()
# 字典同样可以使用copy(),copy.copy(),copy.deepcopy()
# 字典同样遵循和列表一样的深浅拷贝的特征

三、集合

1.概念

Python中的集合跟数学上的集合是一致的,不允许有重复元素,而且可以进行交集、并集、差集等运算

set与dict类似,但是与dict的区别在于只是一组key的集合,不存储value

本质:无序且无重复元素的集合

表示:{},注意:如果直接使用{}则默认表示字典

2.创建

# 1.概念
"""
【面试题】:简述列表,元组,字典,集合和字符串的区别
列表的本质:list,是一种有序的,可变的,可以存储重复元素的,可以存储不同类型的集合
元组的本质:tuple,是一种有序的,不可变的,可以存储重复元素的,可以存储不同类型的集合
字典的本质:dict,是一种有序的【Python3.7之后】,可变的,key不可以重复,
          但是value可以重复,key只能是不可变的数据类型,vlue可以是任意的类型的 集合
集合的本质:set,是一种无序的,可变的,不可以存储重复元素的,可以存储不同类型的集合
字符串的本质:str,是一种有序的,不可变的,可以存储重复字符的集合
"""
​
# 2.定义
# a.定义一个空集合
# {}默认表示字典
dict1 = {}
print(type(dict1))
​
set1 = set()
print(set1)
​
# b.定义一个非空集合
set2 = {3,5,6}
print(set2,type(set2))
​
# c.去重
set3 = {3,3,3,3,4,5,6,6,6,6}
print(set3)
​
# d.无序
set4 = {7,2,45,2,6,7,8,9,10}
print(set4)
​
# 练习:去重一个列表中的重复元素
list1 = [45,67,7,8,2,2,2]
list2 = list(set(list1))
print(list2)

3.集合间的运算

# 3.运算
s1 = {1,2,3}
s2 = {3,4,5}
# 3.1符号
# a.交集
print(s1 & s2)  # {3}
# b.并集
print(s1 | s2)  # {1, 2, 3, 4, 5}
# c.差集
print(s1 - s2)  # {1, 2}
​
# 3.2系统功能
# a.交集
r1 = s1.intersection(s2)  # {3}
print(r1)
# b.并集
r1 = s1.union(s2)  # {1, 2, 3, 4, 5}
print(r1)
# c.差集
r1 = s1.difference(s2)
print(r1)   # {1, 2}

4.集合系统功能

# 集合和字典之间的联系:集合相当于存储了字典中的key

# 一、增
# 1.add(x),x只能是不可变的数据类型,如果x是一个可迭代对象,则整体加入
s1 = {11,22,33}
print(s1)
s1.add(44)
print(s1)
s1.add("abc")
print(s1)
s1.add(True)
print(s1)
s1.add((55,66))
print(s1)
# s1.add([55,66])   # TypeError: unhashable type: 'list'
# s1.add({'a':10})    # TypeError: unhashable type: 'dict'

print("*" * 30)

# 2.update(x),x只能是可迭代对象,只会将可迭代对象中的元素加入【打碎加入】
# 可迭代对象:list,tuple,dict,set,set,range()等容器
s1 = {11,22,33}
print(s1)
# s1.update(44)  # TypeError: 'int' object is not iterable可迭代对象
s1.update("abc")
print(s1)
# s1.update(True)  # TypeError: 'bool' object is not iterable
s1.update((55,66))
print(s1)
s1.update([77,88])
print(s1)
s1.update({'x':10,'y':20})   # 注意:如果x是字典,只能添加key
print(s1)

# 二、删
# 1.remove(x):x表示需要删除的元素     ******
s1 = {11,22,33,4,78,79}
print(s1)
s1.remove(33)
print(s1)
# s1.remove(100)  # KeyError: 100

# 2.pop():因为集合是无序的,所以pop表示随机删除一个
s1 = {11,22,33,4,78,79}
print(s1)
s1.pop()
print(s1)

# 3.discard(x):和remove用法相同,如果被删除的元素不存在,remove会报错,但是discard不会报错  *****
s1 = {11,22,33,4,78,79}
print(s1)
s1.discard(33)
print(s1)
s1.discard(100)

# 4.clear():清空
s1.clear()
print(s1)  # set()

# 三、查
s1 = {11,22,33,4,78,79}
s2 = s1.copy()

print(len(s1))
print(max(s1))
print(min(s1))

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Chiayi_init_

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

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

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

打赏作者

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

抵扣说明:

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

余额充值