编程语言
首页 > 编程语言> > 小渣渣学习笔记 python day08

小渣渣学习笔记 python day08

作者:互联网

p67-

迭代器

l1 = [1,2,3,4] #只是迭代对象
print('__iter__' in dir(l1)) #return True
print('__next__' in dir(l1)) #return False

obj = l1.__iter__() #转化迭代器
print('__iter__' in dir(obj)) #return True
print('__next__' in dir(obj)) #return True
l1 = [1,2,3,4]
print('__iter__' in dir(l1)) #return True
print('__next__' in dir(l1)) #return False
obj = l1.__iter__() #转化迭代器
print('__iter__' in dir(obj)) #return True
print('__next__' in dir(obj)) #return True
a = obj.__next__() #利用next进行取值 
print(a) #return 1
a = obj.__next__()
print(a) #return 2
a = obj.__next__()
print(a) #return 3
a = obj.__next__()
print(a) #return 4
a = obj.__next__()
print(a) #return StopIteration
l1 = [1,2,3,4,5,6]
obj = l1.__iter__() # 将可迭代对象转化成迭代器
while 1: #利用while循环 next取值
    try:
        print(next(obj))
    except StopIteration: #利用异常处理,终止循环
        break
l1 = [1,2,3,4,5,6,]
obj = iter(l1)
for i in range(2):
    print(next(obj)) #return 1,2 每次取一个值
for i in range(2):
    print(next(obj)) #return 3,4
with open('test3.txt',encoding='utf-8',mode='w') as f1:
    print('__iter__' in dir(f1))
    print('__next__' in dir(f1)) #return True 文件句柄是迭代器
l1 = [11,22,33,44,55]
obj = iter(l1) #转化成迭代器
print(next(obj)) #用next取值
print(next(obj))
print(next(obj))
print(next(obj))
print(next(obj))
print(next(obj)) #已经取完,报错 StopIteration

可迭代对象和迭代器的对比

生成器

#1
def func():
    print(11) #return 11
    return 22
ret = func()
print(ret) #return 22
#2
def func():
    print(11) 
    yield 22  #yield 关键字
ret = func()
print(ret) #return <generator object func at 0x037AB3E0>
#
def func():
    print(11)
    yield 22
ret = func()
print(ret.__next__()) #return 11,22

yeild 和 return的区别

列表推导式

#10以内的整数的平方写入列表
l1 = [i**2 for i in range(1,11)]
print(l1) #return [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#100以内的所有的偶数写入列表
l1 = [i for i in range(1,101) if i%2==0]
print(l1)
#从python1期 到 python100期 写入列表中
l1 = ['python'+str(i)+'期' for i in range(1,101)]
print(l1)

#或者
l1 = [f'python{i}期' for i in range(1,101)]
print(l1)
#names = [['Su','Lee','Herry'],['Lucy','Jerry','Tom']] 名字中含有2个r的筛选到一个新列表
names = [['Su','Lee','Herry'],['Lucy','Jerry','Tom']]
l1 = [name for i in names for name in i if name.count('r')==2]
print(l1) #return ['Herry', 'Jerry']

生成器表达式

print([i for i in range(1,11)]) #return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print((i for i in range(1,11))) #return <generator object <genexpr> at 0x02EFB3E0> 变成生成器
#字典推导式
l1=['Jay','Coco','Cindy']
l2=['周杰伦','李玟','王心凌']
dic = {l1[i]:l2[i] for i in range(len(l1))}
print(dic) #return {'Jay': '周杰伦', 'Coco': '李玟', 'Cindy': '王心凌'}

内置函数

标签:__,day08,return,迭代,python,小渣,next,l1,print
来源: https://www.cnblogs.com/94xzz/p/13268767.html