Python day14迭代器,三元表达式,列表解析以及生成器表达式

时间:2021-01-19 17:03:58

1.迭代器

str=['sds','ccc','dw']
lit_1=str.__iter__()#获取迭代器
print(lit_1.__next__())#打印下一个值 # 用while做for的事情
while True:
try:
print(lit_1.__next__())
except StopIteration:
break

2.三元表达式

name='dn'
name='' if name=='dn' else ''

3.列表解析

li=[]
for i in range(10):
li.append(i)
print(li) ri=[i for i in range(10)]
print(ri)
pe=['person%d'%i for i in range(10)]
print(pe)

4.生成器表达式

pe=('person%d'%i for i in range(10))
print(next(pe))

5.生成器函数

def test():
yield 1
yield 2
yield 3
yield 4 r=test()
print(r.__next__())
print(r.__next__())
print(r.__next__())
print(r.__next__()) #yield的案例
def get_infor():
with open('1.txt','r') as f:
for i in f:
yield i
a=get_infor()
print(a.__next__().rstrip())
print(a.__next__().rstrip())
print(a.__next__().rstrip())