搜索
首页后端开发Python教程Python最详细之数据类型讲解

Python教程栏目介绍相关数据类型

Python最详细之数据类型讲解

相关免费学习推荐:python教程(视频)

字符串

字符串的坑:

三引号的字符串如果中间没有双引号的字符串,会在解释器中输出为双引号

三引号的字符串如果中间有双引号的字符串,会在解释器中输出为单引号

字符串是存储在内存中

字符串的操作:

输入:input()

输出:print()

索引:str[index]

取地址: id(str)

切片:str[start: end: step] (负数步长 -- 倒序选取; 选取方向需一致,否则无法选取数据)

查找:find():语法:str.find(substr, start, end)注意:返回值是第一次出现的索引值;如果子串不存在返回-1,不会报错.

例如:mystr = 'hello world and itcast and itheima and Python' print(mystr.find('and')) # 12 print(mystr.find('and',15,30)) # 23 print(mystr.find('ands')) # -1 ands子串不存在 index():

语法: str.index(substr, start, end)返回值是第一次出现的索引值;如果子串不存在,会报错例如:mystr = 'hello world and itcast and itheima and Python'print(mystr.index('and')) # 12 print(mystr.index('and',15,30)) # 23print(mystr.index('ands')) #如果index查找子串不存在,报错 count(): 统计子串出现的次数语法: str.index(substr, tart, end)注意: 返回值是子串出现的次数,如果子串不存在返回0,不会报错例如:mystr = 'hello world and itcast and itheima and Python' print(mystr.count('and',15,30)) # 1 print(mystr.count('and')) # 3print(mystr.count('ands')) # 0 rfind(): 和find()功能相同,但查找方向为右侧开始rindex(): 和index()功能相同,但查找访问为右侧开始

175745016900a263b4cd0ca1faebd58.png

修改:replace() : 替换语法: str.replace(旧子串,新子串, 替换次数)注意:如果不写替换次数,默认会将旧子串全部替换替换次数如果超出子串出现次数,则替换次数为该子串出现的次数。调用replace函数后,发现原有字符串的数据并没有做到修改,修改后的数据是replace函数的返回值 说明: 字符串是不可变数据类型例如: mystr = 'hello world and itcast and itheima and Python' new_str = mystr.replace('and','he') new_str = mystr.replace('and','he',1) new_str = mystr.replace('and','he',10) split() : 分割语法:str.split(分割字符, num)注意:返回值是一个列表, 丢失分割字符num 表示的是分隔字符出现的次数,即将来返回数据个数为num+1个

例如mystr = 'hello world and itcast and itheima and Python' list1 = mystr.split('and') list1 = mystr.split('and',2) join():

合并语法:字符或子串. join(多字符组成的序列)注意:用一个子串或子串合并字符串,即是将多个字符串合并为一个新的字符串例如:mylist = ['aa','bb','cc'] new_str = '...'.join(mylist) print(new_str)

大小写转换capitalize() : 将字符串第一个字符转换成大写语法:str.capitalize()注意:capitalize()函数转换后,只字符串第一个字符大写,其他的字符全都小写

例如:mystr = 'hello world and itcast and itheima and Python' new_str = mystr.capitalize() print(new_str) title(): 将字符串每个单词首字母转换成大写语法: str.title()

例如:mystr = 'hello world and itcast and itheima and Python' new_str = mystr.title() print(new_str) lower(): 将字符串中大写转小写语法: str.lower()注意:全部转为小写

例如: mystr = 'hello world and itcast and itheima and Python'new_str = mystr.lower() print(new_str) upper(): 将字符串中小写转大写语法: str.upper()注意:全部转为小写

例如:mystr = 'hello world and itcast and itheima and Python' new_str = mystr.upper() print(new_str)

删除前后空格lstrip(): 删除字符串左侧空白字符语法: str.lstrip()例如:mystr = ' hello world and itcast and itheima and Python ' new_str = mystr.lstrip() print(new_str) rstrip(): 删除字符串右侧空白字符语法: str.rstrip()

例如:mystr = ' hello world and itcast and itheima and Python ' new_str = mystr.rstrip() print(new_str) strip(): 删除字符串两侧侧空白字符语法: str.strip()

例如:mystr = ' hello world and itcast and itheima and Python ' new_str = mystr.strip() print(new_str)

字符串对齐ljust(): 返回一个原字符串左对齐,并使用指定字符(默认空格)填充至对应长度的新字符串语法: str.ljust(长度,填充字符)例如:mystr = "hello"print(mystr.ljust(10,'.')) 效果为: 'hello.....' rjust(): 返回一个原字符串右对齐,并使用指定字符(默认空格)填充至对应长度的新字符串语法: str.rjust(长度,填充字符)

例如:mystr = "hello" print(mystr.rjust(10,'.')) 效果为: '.....hello' center():返回一个原字符串居中对齐,并使用指定字符(默认空格)填充至对应长度的新字符串语法: str.center(长度,填充字符)例如: mystr = "hello" print(mystr.conter(10,'.')) 效果为: '..hello...'

判断开头结尾startswith(): 检查字符串是否是以指定子串开头,是则返回True,否则返回False。如果设置开始和结束位置下标,则在指定范围内检查语法 : str.startswith(子串,start,end)

例如: mystr = 'hello world and itcast and itheima and Python' print(mystr.startswith('hello')) print(mystr.startswith('hel')) print(mystr.startswith('hels')) endswith(): 检查字符串是否是以指定子串结尾,是则返回True,否则返回False。如果设置开始和结束位置下标,则在指定范围内检查语法:str.endswith(子串,start,end)

例如:mystr = 'hello world and itcast and itheima and Python' print(mystr.endswith('Python')) print(mystr.endswith('Pythons'))

判断isalpha(): 如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False语法: str.isalpha()例如: mystr = 'hello world and itcast and itheima and Python' print(mystr.isalpha()) isdigit(): 如果字符串只包含数字则返回True,否则返回Flase.语法: str.isdigit()

例如:mystr1 = '12345' print(mystr1.isdigit()) isalnum(): 如果字符串至少有一个字符并且所有字符都是字母或数字语法: str.lsalnum()

例如:mystr2 = 'abc123' print(mystr2.isalnum()) isspace(): 如果字符串中只包含空白,则返回True,否则返回False.语法: str.isspace()

例如:mystr3 = ' 'print(mystr3.isspace())

列表

列表的坑:

列表是数据结构的一种具体的体现

列表的格式[数据1, 数据2, 数据3]

在工作中,列表尽可能的存储相同类型的数据

f996dc9aebaeedf6ea849ba649cf43e.png

列表的操作:

增append(): 列表结尾追加数据语法: list.append(数据)注意:列表追加数据的时候,直接在原列表里面追加了指定数据,即修改了原列表,故列表为可变类型数据。如果append()追加的数据是一个序列,则追加整个序列到列表

例如:name_list = ['Tom','Lily','Rost'] name_list.append('xiaoming') print(name_list) # 结果: ['Tom','Lily','Rost','xiaoming'] extend(): 列表结尾追加数据,如果数据是一个序列,则将这个序列的数据逐一添加到列表语法: list.extend(数据)

例如:name_list = ['Tom','Lily','Rost'] name_list.extend('xiaoming') print(name_list) # 结果: ['Tom','Lily','Rost','x','i','a',...] insert(): 指定位置新增数据语法: list.insert(位置下标,数据)例如:name_list = ['Tom','Lily','Rost'] name_list.insert(1, 'xiaoming') print(name_list) # 结果: ['Tom','xiaoming','Lily','Rost']

判断是否存在in:语法: str in list

例如:name_list = ['Tom','Lily','Rost'] print('Lily' inname_list) # True print('Lilys' in name_list) # Flase not in:语法: str not in list例如:name_list = ['Tom','Lily','Rost'] print('Lily' not in name_list) # Flaseprint('Lilys' not in name_list) # True

删del:语法: del 目标例如:name_list = ['Tom','Lily','Rost'] del name_list[0] print(name_list) # ['Lily','Rost'] pop(): 删除指定下标的数据(默认为最后一个),并返回该数据 无论是按照下标还是删除最后一个, pop函数会返回这个被删除的数据语法: list.pop()

例如:name_list = ['Tom','Lily','Rost'] del_name = name_list.pop(1) print(del_name) # 'Lily' print(name_list) # ['Tom','Rost']

remove(): 移除列表中某个数据的第一个匹配项语法: list.remove(数据)

例如: name_list = ['Tom','Lily','Rose'] name_list.remove('Rose') print(name_list) # ['Tom','Lily'] clear(): 清空列表语法: list.clear()例如: name_list = ['Tom','Lily','Rost'] name_list.clear() print(name_list) # []

改修改指定下标数据

例如:name_list = ['Tom','Lily','Rost'] name_list[0] = 'aaa'print(name_list) # ['aaa','Lily','Rost'] reverse() :逆置语法: list.reverse()

例如:num_list = [1,5,2,3,6,8] num_list.reverse() print(num_list) # [8,6,3,2,5,1]sort(): 排序语法: list.sort(key=None,reverse=False)注意: reverse表示排序规则, reverse = True 降序, reverse = False 升序(默认)

例如:num_list = [1,5,2,3,6,8] num_list.sort() print(num_list) # [1,2,3,5,6,8]

查下标:index(): 返回指定数据所在位置的下标 -- 如果查找的数据不存在则报错语法: list.index(数据,start,end)例如:name_list = ['Tom','Lily','Rose'] print(name_list.index('Lily',0,2)) # 1 count(): 统计指定数据在当前列表中持续的次数语法: list.count()

例如:name_list = ['Tom','Lily','Rose'] print(name_list.count('Lily')) len(): 访问列表长度,即列表中数据的个数语法: len(list)

例如:name_list = ['Tom','Lily','Rose'] print(len(name_list)) # 3

复制copy(): 开辟新空间存储数据语法: list.copy()例如:name_list = ['Tom','Lily','Rose'] name_li2 = name_list.copy() print(name_li2) # ['Tom','Lily','Rose']

遍历while: 依次打印列表中的各个数据例如:name_list = ['Tom','Lily','Rose'] i = 0 while i < len(name_list): print(name_list[i]) i +=1 # 结果:Tom Lily Rose for: 依次打印列表中的各个数据例如:name_list = ['Tom','Lily','Rose'] for i in name_list: print(i) # 结果:Tom Lily Rose

列表嵌套概念: 列表嵌套指的就是一个列表里面包含了其他的子列表

例如:name_list = [['小明','小红','小绿'],['Tom','Lily','Rose'],['张三','李四','王二']] print(name_list[2]) # ['张三','李四','王二'] print(name_list[2][1]) # 李四

元组

元组的坑:

一个元组可以存储多个数据, 元组内的数据是不能修改的

元组的格式: (数据1, 数据2, 数据3)

如果定义的元组只有一个数据,那个这个数据后面也最好添加逗号, 否则数据类型为唯一的这个数据的数据类型

在工作中,元组尽可能的存储相同类型的数据

元组的操作:

查找按下标查找数据:例如:tuple1 = ('aa','bb','cc','bb') print(tuple1[0]) # aaindex(): 查找某个数据,如果数据存在返回对应的下标,否则报错语法: 语法和列表、字符串的index方法相同 -- tuple.index(子串)例如:tuple1 = ('aa','bb','cc','bb') print(tuple1.index('aa')) # 0 count(): 统计某个数据在当前元组出现的次数语法: tuple.count(数据)例如:tuple1 = ('aa','bb','cc','bb') print(tuple1.count('bb')) # 1len() : 统计元组中数据的个数语法: len(tuple)例如:tuple1 = ('aa','bb','cc','bb') print(len(tuple1)) # 4

修改元组内的直接数据如果修改则立即报错例如:tuple1 = ('aa','bb','cc','bb') tuple1[0] = 'aaa' # 报错 如果元组里面有列表,修改列表里面的数据例如:tuple2 = (10, 20, ['aa', 'bb', 'cc'], 50, 30) print(tuple2[2]) # 访问到列表 tuple2[2][0] = 'aaaaa' print(tuple2) # (10, 20, ['aaaaa', 'bb', 'cc'], 50, 30)

字典

字典的坑:

字典里面的数据是以键值对形式出现,字典数据和数据顺序没有关系,即字典不支持下标,后期无论数据如何变化,只需要按照对应的键的名字查找数据即可

字典的格式: {'key1':value1, 'key2':value2}

字典的操作:

增dict[key] = value:语法: 字典系列[key] = 值注意: 如果key存在则修改这个key对应的值,如果key不存在则新增此键值对。字典为可变类型例如:dict1 = {'name':'Tom', 'age':20; 'gender':'男'} dict1['name'] = 'Rose' print(dict1) # {'name':'Rose', 'age':20; 'gender':'男'} dict1['id'] = 110 print(dict1) # {'name':'Tom', 'age':20; 'gender':'男', 'id':110} dict(zip(list1,list2)):语法: dict(zip(list1,list2))注意:两个列表的数据个数需要一样例如:a = [1,2,3,4] b = [1,2,3,4] c = dict(zip(a,b)) print(c) # {1:1, 2:2, 3:3, 4:4}

删del()/ del: 删除字典或删除字典中指定键值对语法: del dict例如:dict1 = {'name':'Tom', 'age':20, 'gender':'男'} del dict1['gender'] print(dict1) # {'name':'Tom', 'age':20} clear(): 清空字典语法:dict.clear()例如:dict1 = {'name':'Tom', 'age':20, 'gender':'男'} dict1.clear() print(dict1) # {}

改修改:语法: 字典序列[key] = 值注意: 如果key存在则修改这个key对应的值,如果key不存在就新增此键值对例如:dict1 = {'name':'Tom', 'age':20; 'gender':'男'} dict1['name'] = 'Rose' print(dict1) # {'name':'Rose', 'age':20; 'gender':'男'}

查key查找语法: dict[key]注意: 如果当前查找的key存在,则返回对应的值;否则报错例如:dict1 = {'name':'Tom', 'age':20; 'gender':'男'} print(dict1['name']) # Tomprint(dict1['id']) # 报错 get()语法: 字典序列.get(key, 默认值)注意: 如果当前查找的key不存在则返回第二个参数(默认值),如果省略第二个参数,则返回None例如:dict1 = {'name':'Tom', 'age':20; 'gender':'男'} print(dict1.get('name')) # Tomprint(dict1.get('id',100)) # 100 print(dict1.get('id')) # None keys()语法: dict.keys()例如:dict1 = {'name':'Tom', 'age':20; 'gender':'男'} print(dict1.keys()) # dict_keys(['name','age','gender']) values()语法: dict.values()例如:dict1 = {'name':'Tom', 'age':20; 'gender':'男'} print(dict1.values()) # dict1.values(['Tom',20,'']) items()语法: dict1.items()例如:dict1 = {'name':'Tom', 'age':20; 'gender':'男'} print(dict1.items()) # dict_items([('name','Tom'),('age',20),('gender','男')])

遍历遍历字典的key例如dict1 = {'name':'Tom', 'age':20; 'gender':'男'} for key indict1.keys(): print(key) # 结果: name age gender 遍历字典的values例如:dict1 = {'name':'Tom', 'age':20; 'gender':'男'} for key in dict1.values(): print(key) # 结果: Tom 20 男 遍历字典的元素例如:dict1 = {'name':'Tom', 'age':20; 'gender':'男'} for key in dict1.items(): print(key) # 结果: ('name','Tom') ('age',20) ('gender','男') 遍历字典的键值对(拆包)例如:dict1 = {'name':'Tom', 'age':20; 'gender':'男'} for key,values in dict1.items(): print(f'{key} = {values}') # 结果: name = Tom age = 20 gender = 男

集合

集合的坑:

创建集合使用{}或set(),但是如果要创建空集合只能使用set(),因为使用{}创建的是字典

集合不支持下标操作,因为集合没有顺序

集合数据有去重功能

c689f4c7c1b2da90a2a88eb125501c9.png

集合的操作:

增加数据add()语法: set.add()注意:因为集合有去重功能,所以,当向集合内追加数据是当前集合已有数据的话, 则不进行任何操作例如:s1 = {10,20} s1.add(100) s1.add(10) print(s1) # {100, 10, 20} update():语法: set.update(list)注意: 追加的数据是序列例如:s1 = {10, 20} # s1.update(100) # 报错 s1.update([100, 200]) s1.update('abc') print(s1) # {'c', 100, 'a', 200, 10, 20, 'b'}

删除数据remove()语法: set.remove()注意: 删除集合中的指定数据,如果数据不存在则报错例如:s1 = {10, 20} s1.remove(10) print(s1) # {20} s1.remove(10) print(s1) # 报错 discard()语法: set.discard()注意: 删除集合中的指定数据, 如果数据不存在也不会报错例如:s1 = {10, 20} s1.discard(10) print(s1) s1.discard(10) print(s1) pop()语法: set.pop()注意: 随机删除集合中的某个数据,并返回这个数据例如:s1 = {10, 20, 30, 40 ,50} del_num = s1.pop() print(del_num) print(s1)

查找数据in : 判断数据在集合序列not in :判断数据不在集合序列例如:s1 = {10, 20, 30, 40, 50} print(10 in s1) print(10 not in s1)

公共操作

运算符

运算符描述支持的容器类型+合并字符串、列表、元组*复制字符串、列表、元组in元素是否存在字符串、列表、元组、字典、集合not in元素是否不存在字符串、列表、元组、字典、集合

例如:

# +# 1. 字符串str1 ='aa'str2 ='bb'str3 = str1 + str2print(str3)# aabb# 2. 列表list1 = [1, 2]list2 = [10, 20]list3 = list1 + list2print(list3)# [1, 2, 10, 20]# 3. 元组t1 = (1, 2)t2 = (10, 20)t3 = t1 + t2print(t3)# (10, 20, 100, 200)# * # 1. 字符串print('-'* 10)# ----------# 2. 列表list1 = ['hello']print(list1 * 4)# ['hello', 'hello', 'hello', 'hello']# 3. 元组t1 = ('world',)print(t1 * 4)# ('world', 'world', 'world', 'world')# in 或 not in # 1. 字符串print('a'in'abcd')# Trueprint('a'notin'abcd')# False# 2. 列表list1 = ['a','b','c','d']print('a'inlist1)# Trueprint('a'notinlist1)# False# 3. 元组t1 = ('a','b','c','d')print('aa'int1)# Falseprint('aa'notint1)# True

公共方法

函数描述len()计算容器中元素个数del 或 del()删除max()返回容器中元素最⼤值min()返回容器中元素最⼩值range(start, end, step)⽣成从start到end的数字,步⻓为 step,供for循环使⽤enumerate()函数⽤于将⼀个可遍历的数据对象(如列表、元组或字符串)组合为⼀个索引序 列,同时列出数据和数据下标,⼀般⽤在 for 循环当中

例如:

# len()# 1. 字符串str1 ='abcdefg'print(len(str1))# 7# 2. 列表list1 = [10,20,30,40]print(len(list1))# 4# 3. 元组t1 = (10,20,30,40,50)print(len(t1))# 5# 4. 集合s1 = {10,20,30}print(len(s1))# 3# 5. 字典dict1 = {'name':'Rose','age':18}print(len(dict1))# 2# del()# 1. 字符串str1 ='abcdefg'delstr1print(str1)# 2. 列表list1 = [10,20,30,40]del(list1[0])print(list1)# [20, 30, 40]# max()# 1. 字符串str1 ='abcdefg'print(max(str1))# g# 2. 列表list1 = [10,20,30,40]print(max(list1))# 40# min()# 1. 字符串str1 ='abcdefg'print(min(str1))# a# 2. 列表list1 = [10,20,30,40]print(min(list1))# 10# range() -- range()生成的序列不包含end数字# 1 2 3 4 5 6 7 8 9foriinrange(1,10,1): print(i)# 1 3 5 7 9foriinrange(1,10,2): print(i)# 0 1 2 3 4 5 6 7 8 9foriinrange(10): print(i)# enumerate() -- enumerate(可遍历的对象, start=0)list1 = ['a','b','c','d','e']foriinenumerate(list1): print(i)forindex, charinenumerate(list1, start=1): print(f'下标是{index}, 对应的字符是{char}')

容器类型的转换

tuple()作用: 将某个序列转换成元组例如list1 = [10, 20, 30, 40, 50, 20] s1 = {100, 200, 300, 400, 500} print(tuple(list1)) print(tuple(s1))

list()作用: 将某个序列转换成列表例如:t1 = ('a', 'b', 'c', 'd', 'e') s1 = {100, 200, 300, 400, 500} print(list(t1)) print(list(s1))

set()作用: 将某个序列转换成集合例如:list1 = [10, 20, 30, 40, 50, 20] t1 = ('a', 'b', 'c', 'd', 'e') print(set(list1)) print(set(t1)) # 1. 集合可以快速的完成列表去重 # 2. 集合不支持下标

推导式 -- 生成式

列表推导式作用:用一个表达式创建一个有规律的列表或控制一个有规律列表例如:# while 循环实现 # 1. 准备一个空列表 list1 = [] # 书写循环,依次追加数字到空列表list1中 i = 0 while i < 10: list1.append(i) i += 1 print(list1) # for 循环实现 list1 = [] for i in range(10): list1.append(i) print(list1) # 列表推导式实现 list1 = [i for i in range(10)] print(list1) # 带if的列表推导式 # 方法一: range()步长实现 list1 = [i for i in range(0,10,2)] print(list1) # 方法二: 带if的列表推导式 list1 = [i for i inrange(10) if i % 2 == 0] print(list1) # 多个for循环实现列表推导式 list1 = [(i, j)fori in range(1, 3)for j in range(3)] print(list1)

字典推导式作用: 快速合并列表为字典或提取字典中的目标数据例如:# 1. 创建一个字典:字典的key是1-5数字, value是这个数字的平方 dict1 = {i:i**2 for i in range(1, 5)} print(dict1) # {1: 1, 2: 4, 3: 9, 4: 16} # 2. 将两个列表合并为一个字典 list1 = ['name', 'age', 'gender'] list2 = ['Tom', 20, 'man'] dict1 = {list1[i]: list2[i] for i inrange(len(list1))} print(dict1) # 3. 提取字典中的目标数据 counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99} # 需求: 提取上述电脑数量大于等于200的字典数据 count1 = {key: value for key, value in counts.items() if value >= 200} print(count1) # {'MBP':268, 'DELL': 201}

集合推导式作用: 快速生成集合,集合有数据去重功能例如:# 创建一个集合, 数据为下方列表的2次方 list1 = [1, 1, 2] list1 = [1, 1, 2] set1 = {i ** 2 for i in list1} print(set1) # {1, 4}

Python中的小整数对象池和大整数对象池,以及“is” 和“==”的区别

Python是一门弱变量类型语言,变量使用之前无需声明变量的类型。对于一个变量有三个属性:id(内存地址),type(变量类型),value(值)

对于=, == , is的区别:= 赋值操作,传递的是id, type, value== 判断的是value是否相等is 判断id是否相等

小整数对象池对于小整数对象使用了对象池技术。设置小整数的范围为[-5,256]。在这个范围内的小整数,任意相同的整数都是同一个对象,同理,单个字母也是这样的小整数的缓冲池是在Python初始化的时候被创建的intern机制处理空格一个单词的复用机会大,所以创建一次,有空格创建多次,但是字符串长度大于20,就不是创建一次了a = -5 b = -5 a is b # True a = 256 b = 256 a is b # True a = 1000 b = 1000 a is b # True a = 'abc' b = 'abc' a is b # True a = 'helloworld' b = 'helloworld' a is b # True a = 'hello world' b = 'hello world' a is b # False

大整数对象池超出小整数的范围即为大整数,每次都会创建一个新的对象。但是处于一个代码块的大整数是同一个对象。终端是每次执行一次,所以每次的大整数都重新创建,而在pycharm中,每次运行是所有代码都加载都内存中,属于一个整体,所以这个时候会有一个大整数对象池,即处于一个代码块的大整数是同一个对象在pycharm中,每次运行是所有代码都加载都内存中,属于一个整体,所以这个时候会有一个大整数对象池,即处于一个代码块的大整数是同一个对象a = 1000 b = 1000 a is b # False a = -1888 b = -1888 a is b # False class C1(object): a = 100 b = 100 c = 1000 d = 1000 class C2(objcet): a = 100 b = 1000 print(C1.a is C1.b) # True print(C1.a is C1.a) # True print(C1.c is C1.d) # True print(C1.d is C1.b) # Falsec

生成器

生成器的作用根据程序设计者制定的规则循环生成数据,当条件不成立时生成数据结束数据不是一次性全部生成出来,而是使用一个,再生成一个,可以节约大量的内存

生成器的创建生成器推导式生成器推导式与列表推导式相似,不过列表推导式使用小括号# 创建生成器 my_generator = (i * 2 for i in range(5)) print(my_generator)

yield 关键字:yield关键字生成器的特性:在def函数中具有yield关键字defmygenerator(n): for i in range(n): print('开始生成...') yield i print('完成一次...') 注意点:代码执行到yield会暂停,然后把结果返回出去,下次启动生成器会在暂停的位置继续往下执行生成器如果把数据生成完成,再次获取生成器中的下一次数据会抛出一个StopIteration异常,表示停止迭代异常while循环内部没有处理异常操作,需要手动添加处理异常操作for循环内部自动处理了停止迭代异常,使用起来更加方便,

生成器相关函数next函数获取生成器中的下一个值for循环遍历生成器中的每一个值

相关免费学习推荐:编程视频

以上是Python最详细之数据类型讲解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:简书。如有侵权,请联系admin@php.cn删除
Python:探索其主要应用程序Python:探索其主要应用程序Apr 10, 2025 am 09:41 AM

Python在web开发、数据科学、机器学习、自动化和脚本编写等领域有广泛应用。1)在web开发中,Django和Flask框架简化了开发过程。2)数据科学和机器学习领域,NumPy、Pandas、Scikit-learn和TensorFlow库提供了强大支持。3)自动化和脚本编写方面,Python适用于自动化测试和系统管理等任务。

您可以在2小时内学到多少python?您可以在2小时内学到多少python?Apr 09, 2025 pm 04:33 PM

两小时内可以学到Python的基础知识。1.学习变量和数据类型,2.掌握控制结构如if语句和循环,3.了解函数的定义和使用。这些将帮助你开始编写简单的Python程序。

如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础?如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础?Apr 02, 2025 am 07:18 AM

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到?如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到?Apr 02, 2025 am 07:15 AM

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

Python 3.6加载Pickle文件报错"__builtin__"模块未找到怎么办?Python 3.6加载Pickle文件报错"__builtin__"模块未找到怎么办?Apr 02, 2025 am 07:12 AM

Python3.6环境下加载Pickle文件报错:ModuleNotFoundError:Nomodulenamed...

如何提高jieba分词在景区评论分析中的准确性?如何提高jieba分词在景区评论分析中的准确性?Apr 02, 2025 am 07:09 AM

如何解决jieba分词在景区评论分析中的问题?当我们在进行景区评论分析时,往往会使用jieba分词工具来处理文�...

如何使用正则表达式匹配到第一个闭合标签就停止?如何使用正则表达式匹配到第一个闭合标签就停止?Apr 02, 2025 am 07:06 AM

如何使用正则表达式匹配到第一个闭合标签就停止?在处理HTML或其他标记语言时,常常需要使用正则表达式来�...

如何绕过Investing.com的反爬虫机制获取新闻数据?如何绕过Investing.com的反爬虫机制获取新闻数据?Apr 02, 2025 am 07:03 AM

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。