栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python Note — Day 8. 数据类型详解

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python Note — Day 8. 数据类型详解

14.8 数据类型详解- 元组

元组和列表一样都是一组有序的数据的组合
元组中的元素一旦定义不可修改,为不可变数据类型

14.8.1 元祖定义

  • 定义空元祖 变量=0 或者 变量=tuple()
  • 元组中只有一个元素时,必须添加逗号,变量=(1,)
  • 特例,变量=1,2,3 这种方式也可定义为一个元组

14.8.2 元祖的相关操作

  • 由于元组不可变的数据类型,只能使用索引进行访问,不能进行其他操作!!
  • 元组可以和列表一样使用切片方式获取元素
# 获取长度
vars = 1,2,3,55
res = len(vars)
print(res)

# 统计一个元素在元组中出现的次数
res = vars.count(5)
print(res)

# 获取一个元素在元组的索引值
res = vars.index(55,1) # 从指定下表位置开始查找
res = vars.index(55,1,5) # 从指定 索引区间内查找
print(res)

# 元组 + * 运算,合并元组
res = (1,2,3) + ('a','b')
res = (1,2,3)*2
print(res)

# 检测元素是否在元组中
res = 2 in vars
res = 2 not in vars
print(res)

14.8.3 元组推导式 生成器

列表推导式返回的结果是一个列表,元组推导式返回生成器

(变量运算 for i in 容器)

  • 生成器generator:
    生成器是一个特殊的迭代器,生成器可以自定义,也可使用元组推导式去定义
    生成器是按照某种算法去推算下一个数据结果,只需往内存中存储一个生成器,节约内存消耗,提升性能
  • 语法:
    1)里面是推导式,外面是一个()的结果就是一个生成器
    2)自定义生成器,含有yield关键字的函数就是生成器
    含有yield关键字的函数,返回结果是一个迭代器,生成器就是一个返回迭代器的函数
  • 使用生成器:
    生成器是迭代器的一种,可以使用迭代器的操作方法来操作生成器
varlist = [1,2,3,4,5,6,88,99]
# 列表推导式
new = [i**2 for i in varlist]
print(new)
# 元组推导式
news = (i**2 for i in varlist)
print(news)
# 使用next()函数调用
print(next(news))
# 使用list()或tuple()函数操作
print(list(news))
print(tuple(news))
# 使用 for 进行遍历
for i in news:
    print(i)

14.8.4 生成器与yield关键字

yield关键字使用在 生成器函数中
— yield 和函数中 return 有点像
共同点:执行到这个关键字后会把结果返回
不同点:
return 会把结果返回,并结束当前函数的调用;
yield 会返回结果,并记住当前代码执行的位置,下一次调用时会从上一次离开的位置继续向下执行

# 普通函数中 return 
def he():
    print('hello')
    return 1  # 结束在此,后面不执行
    print('w')
    return 2
he()
print(he())

# yield定义一个生成器函数
def hee():
    print('hello')
    yield 1
    print('with')
    yield 2
next(hee())  # hello
res = hee()
# next(res)    # hello
# next(res)    # with
# 使用生成器返回的迭代器
r = next(res)
print(r)          
r = next(res)
print(r)

for i in res:
    print(i)
  • 使用list类似的函数 去调用生成器返回的迭代器时,会把迭代器的返回结果,作为容器的元素
def hee():
    print('hello')
    yield 1
    print('with')
    yield 2
res = hee()
t = list(res)
print(t)
                            '''返回的是
                            hello
                            with
                            [1, 2]
                            '''

生成器函数调用时的过程:
首先 调用生成器函数,返回一个迭代器
1.第一次去调用迭代器
走到当前的生成器函数中,遇到 yield 1,把1返回,并且记住当前执行状态(位置),暂停执行,等待下一次调用
2.第二次调用迭代器
从上一次遇到的yield 位置开始执行,遇到 yield 2,把2返回,并且记住状态(位置),暂停执行,等待下一次调用
3.第三次调用迭代器
从上一次遇到的yield 位置开始执行,遇到 yield 3,把3返回,并且记住状态,暂停执行,等待下一次调用
……
若在最后又调用迭代器,那么会从上一次的的yield 位置开始执行,后面没有,直接超出范围,报错

14.8.4 练习题

1.使用生成器改写斐波那契数列
1,1,2,3,5,8,

# 1,1,2,3,5,8,13
def fibo(num):
    a,b,i = 0,1,0
    while i < num:
        yield b   # 原:print(b,end=' ')
        a,b = b,a+b
        i+=1
# res = fibo(6)
# print(res)
# print(list(res))

num = int(input('please enter a positive int: '))
for i in fibo(num):
    print(i,end=' ')
def fibo():
    a,b,i = 0,1,0
    while True:
        yield b
        a,b = b,a+b
        i+=1
num = int(input('please enter a positive int: '))
res = fibo()
for i in range(1,num+1):
    print(next(res),end=' ')
14.9 数据类型详解- 字典

映射类型

14.9.1 字典的定义

由键值对组成的数据集合,键不能重复
字典中的键必须是不可变的数据类型
一般通过 以逗号分隔的键:值 对的列表包含于花括号之内来创建,也可通过 dict构造器 创建

# 2.使用 dict(key=value,key=value) 函数进行定义
vardict = dict(name='Beth',age=30,sex='male')
print(vardict)

# 3.使用数据类型的转换  dict(二级容器类型:列表或元组)
vardict = dict([['a',1],['b',2]])
print(vardict)

# 4.zip压缩函数,dict转类型,转换的原理和3一个原理
var1 = [1,2,3,4]
var2 = ['a','b','c',7]
vardict = dict(zip(var1,var2))  # {1: 'a', 2: 'b', 3: 'c', 4: 7}
vardict = list(zip(var1,var2))  # [(1, 'a'), (2, 'b'), (3, 'c'), (4, 7)]
print(vardict)

14.9.2 字典的操作

TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
unsupported operand type(s) for *: 'dict' and 'int'
无法确定key如何去操作

  • 获取元素
dict1 = {'name': 'Beth', 'age': 30, 'sex': 'male'}
res = dict1['name']
  • 修改元素
dict2 = {'a': 1, 'b': 2}
res = dict2['a'] = 33
print(res)
  • 删除元素
del dict1['sex']
print(dict1)
  • 添加元素,若字典中key重复了,会被覆盖
dict2 = {'a': 1, 'b': 2}
dict2['c']= 7
print(dict2)
  • 成员检测,只能检测key,不能测value
dict1 = {'name': 'Beth', 'age': 30, 'sex': 'male'}
res = 'age' in dict1
print(res)
  • 获取字典长度,只能检测键值对
    res = len(dict1)
  • 获取字典中的所有key
dict1 = {'name': 'Beth', 'age': 30, 'sex': 'male'}
res = dict1.keys()   # dict_keys(['name', 'age', 'sex', 'a'])
print(res)
  • 获取字典中的所有value
    res = dict1.values()
  • 获取字典中的所有键值对
    res = dict1.items()
  • 对字典进行遍历
# 1) 用for对字典进行遍历,只能获取key
dict1 = {'name': 'Beth', 'age': 30, 'sex': 'male'}
for i in dict1:
    print(i)
    print(dict1[i]) # 通过key获取value

# 2) 遍历字典时,使用items()函数,可以在遍历中获取key和value
for x,y in dict1.items():
    print(x)
    print(y)

# 3) 遍历所有key
for k in dict1.keys():
    print(k)

# 4) 遍历所有value
for k in dict1.values():
    print(k)

14.9.3 字典的相关函数

  • len(dict) 获取字典的键值对个数
  • dict.keys() 获取字典所有key,组成的列表
  • dict.values() 获取字典所有value,组成的列表
  • dict.items() 获取字典项((键,值)对),组成的一个新视图
  • clear()
  • copy()
  • iter(d) 返回以字典的键为元素的迭代器
dict1 = {'a': 1, 'b': 2,'c':3}
res = iter(dict1)
print(res)
print(next(res))
  • dict.pop(key[,default])
    若key存在字典中则将其移除并返回其值,否则返回default。若default未给出且key不存在于字典中,则会引发keyerror
dict1 = {'a': 1, 'b': 2,'c':3}
res = dict1.pop('a')
print(res)
  • dict.popitem()
    把最后加入的键值对移除,并返回一个元组 LIFO:last in, first out
res = dict1.popitem()
print(res) # ('c', 3)
  • dict.get(key)
    获取不存在元素时,不会报错,默认返回None
  • dict.update([other]),更新字典,或添加元素
dict1 = {'a': 1, 'b': 2,'c':3}
res = dict1.update(a=11,b=22)
print(dict1)
dict1.update({'c':44,'d':5})
print(dict1)
  • dict.setdefault(key[,value])
    字典存在key,返回它的值,若不存在,插入值为default的键key,并返回default。default默认为None
dict1 = {'a': 1, 'b': 2,'c':3}
res = dict1.setdefault('a')
print(res) # 1
res = dict1.setdefault('aa')
print(res) # None
print(dict1) # {'a': 1, 'b': 2, 'c': 3, 'aa': None}
res = dict1.setdefault('bb',55)
print(res) # 55

14.9.3 字典推导式

  • 把字典中键值对进行交换
dict1 = {'a': 1, 'b': 2,'c':3}
new = {}
for k,v in dict1.items():
    new[v]=k
print(new)

# 字典推导式
new = {v:k for k,v in dict1.items()}
print(new)

# 注意:以下推导式,返回结果是一个集合,集合推导式
new = {v for k,v in dict1.items()}
print(new)
  • 把字典中是偶数的值保留下来,并交换键值对的位置
new = {v:k for k,v in dict1.items() if v % 2 == 0}
print(new)
14.10 数据类型详解- 集合

确定的一组无需的数据的组合

  • 确定的 : 当前集合中元素的值不能重复
  • 由多个数据组合的复合型数据(容器类型)
  • 集合中的数据没有顺序
  • 功能:成员检测、从序列中去除重复项及数学中的集合类计算,如交集、并集、差集和对称差集等等

14.10.1 集合的定义

  • 直接使用{}来定义集合
  • 使用set()进行集合的定义和转换
  • 使用集合推导式完成 注意:集合中元素不能重复,集合中存放的数据:Number,Strings,Tuple,Frozenset

14.10.2 集合的基本操作和常规函数

vars = {13,'abc','love',True,(1,2,3),0,3.1415,13,False}
print(vars)  # {0, True, 3.1415, 'love', 'abc', 13, (1, 2, 3)}
# 1. 无序  
# 2. False在集合中表示为0,所以False和0只能存在一个
# 3. 元素的值不能重复
  • 检测集合中的值
    res = '13' in vars
    res = '13' not in vars
    print(res)
  • 检测集合种元素的个数 len(set)
    res = len(vars)
  • 集合的遍历
vars = {13,'abc','love',True,(1,2,3),0,3.1415,13,False}
for i in vars:
    print(i)
  • 向集合中追加元素 add(elem),update(other sets)
vars = {13,'abc','love',True,(1,2,3),0,3.141}
res = vars.update({1,44})
res = vars.add('de')
print(vars)
  • 删除集合中元素 pop(),remove(elem),discard(elem)
# pop()随机删,无法返回
vars = {13,'de','love',True,(1,2,3),0,3.1415,13}
res = vars.add('de')
print(vars)
res = vars.pop()
print(vars)
res = vars.pop()
print(vars)

# 指定删除集合中的元素,remove() 返回None,不存在则报错
res = vars.remove('de')
print(res)
print(vars)

# 指定删除集合中的元素,set.discard(elem),不存在也不会报错
res = vars.discard(13)

# 清空集合 clear()
vars.set()
print(vars) # set()
  • 集合的浅复制 copy(),集合中不存在深拷贝的问题
    因为集合中的元素都是不可变,包括元组和冰冻集合
    不存在拷贝后,对集合中不可变的二级容器进行操作的问题
vars = {0, True, 3.1415, 13, (1, 2, 3), 'love', 'abc'}
res = vars.copy()
for i in res:
    if isinstance(i,tuple):
        print(i)
  • 冰冻集合(了解)
'''
语法:定义冰冻集合,只能使用frozenset()函数
+ 冰冻集合一旦定义不能修改
+ 冰冻集合只能做集合相关的元素,交集并集等
+ frozenset()本身就是一个强制转换类的函数,可把其他任何容器类型的数据转为冰冻集合
'''
v = frozenset((1,2,3))
t = frozenset({'a','b'})
print(v,t)

# 遍历
for i in v:
    print(i)

# 冰冻集合的推导式
res = frozenset({i<<1 for i in range(5)})
print(res)

# copy()
res = v.copy()

# 冰冻集合可以和普通集合一样进行集合运算

14.10.3 集合的推导式

1.普通推导式

varset = {1,2,3,4}
newset = {i<<1 for i in varset}
print(newset)

2.带有条件表达式的推导式

newset = {i for i in varset if i % 2 == 1}

3.带有多循环的集合推导式

var1 = {1,2,3,4}
var2 = {4,7,8,}
new = set()
for i in var1:
    for j in var2:
        new.add(i+j)
print(new)
# 推导式
newset = {i+j for i in var1 for j in var2}
print(newset)

4.带有条件表达式的多循环的集合推导式

newset = {i+j for i in var1 for j in var2 if i % 2 ==0 and j % 2 ==0}
print(newset)

14.10.4 集合运算

1.集合运算符号

A和B的交集 & :A和B中共有的部分,包含一个字符串中相同的部分
A和B的并集 | :两个集合所有元素集中起来,去掉重复的部分
A和B的差集 - :A有B没有
B和A的差集 - :B有A没有
A和B的对称差集 ^ :A和B中除了共有部分的其他部分
C中包含D集合的元素,c为超集,D为子集

var1 = {'11',1,'lil',54}
var2 = {'11',False,'lily',54,True}
r1 = var1 & var1
print(r1)   # {1, '11', 'lil', 54}
r2 = var1 - var2
print(r2)   # {'lil'}
r3 = var2 - var1
print(r3)   # {False, 'lily'}
r4 = var1 ^ var2
print(r4)   # {False, 'lil', 'lily'}
r5 = var1 | var2
print(r5)   # {False, 1, 'lil', 54, '11', 'lily'}
  • 交集运算函数 set.intersection(),set.intersection_update()
    不包含一个字符串中相同部分
# intersection() 返回交集的结果
var1 = {'11',1,'lil',54}
var2 = {'11',False,'lily',54,True}
r11 = var1.intersection(var2)
print(r11)  # {1, '11', 54}

# intersection_update() 计算两个集合相交的部分,把计算结果重新赋值给第一个集合
print(var1)  # {1, '11', 54, 'lil'}
r111 = var1.intersection_update(var2)
print(r111)  # None
print(var1)  # {'11', 1, 54}

2.集合运算函数

  • 并集的运算函数 union(),update()
# 返回并集的结果,新的集合
r55 = var1.union(var2)
print(r55)   # {'11', 1, 'lil', False, 'lily', 54}
# 求并集运算,并把结果赋值给第一个集合
r555 = var1.update(var2)
print(r555)  # None
print(var1)  # {'11', 1, 'lil', False, 'lily', 54}
  • 差集的运算函数 difference(),difference_update()
r22 = var1.difference(var2)
print(r22)
r222 = var1.difference_update(var2)
print(var1)
  • 对称差集的运算函数 symmetric_difference(),symmetric_difference_update()
r44 = var1.symmetric_difference(var2)
print(r44)
r444 = var1.symmetric_difference_update(var2)
#print(var1)
print(r444)  # None

3.检测超集和子集

  • issuperset() 检测是否为超集
  • issubset() 检测是否为子集
var1 = {1,2,3,4,5}
var2 = {1,2}
res = var1.issuperset(var2)
print(res)
re = var2.issubset(var1)
print(re)

4.检测两个集合是否 不相交 isdisjoint()
re1 = var1.isdisjoint(var2)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/293554.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号