Python入门之yield表达式,三元表达式与生成式

本文介绍了Python编程中生成器和表达式的使用,包括如何使用`yield`关键字创建生成器,以及列表生成式、字典生成式、集合生成式和生成器表达式的实践案例。通过这些例子,展示了它们在处理序列、字典和集合数据时的高效能和内存优化特性。同时,还探讨了三元表达式的简洁写法以及文件读取的多种方式。
摘要由CSDN通过智能技术生成
#x=yield 返回值

def l(name):
    print('loky%s准备吃东西'%name)
    while True:
        x=yield None
        print('loky%s吃了%s'%(name,x))

a=l('1')

# print(a)
# res=next(a)
# print(res)
a.send(None)#等同于next(a)
a.send(123)
a.send('鸡肉')
next(a)#None返回

a.close()#关闭之后无法传值,不能穿两个值,但是可以传列表,之后解压赋值,但这不是yield的用处了
a.send(1123)

#三元表达式

#针对一下需求

# def func(x,y):
#     if x>y:
#         return x
#     else:
#         return y
#
# res=func(1,2)
# print(res)

#三元表达式

#语法格式:条件成立是要返回的值 if 条件 else 条件不成立要返回的值
x=1
y=2
res=x if x>y else y
print(res)

#生成式

#列表生成是式

l=['loky_1','luce_1','doky']
# new_l=[]
# for i in l:
#     if i.endswith('1'):
#         new_l.append(i)
# print(new_l)
# new_l=[i for i in l if i.endswith('1')]
# print(new_l)
#把所有的小写变成大写
# new_l=[i.upper()for i in l]
# print(new_l)

#把所有名字去掉后缀_1

# new_l=[i.replace('_1','') for i in l]
# print(new_l)



#2、字典生成式


# keys=['name','age','gender']
#
# dic={key:None for key in keys}
# print(dic)
# items=[('name','loky'),('age',18),('sex','female')]
#
# dic={i:j for i,j in items if i!='sex'}
# print(dic)


#3、集合生成式
# keys={'name','age','sex'}
# res={key for key in keys }
# print(res,type(res))

#注意没有元组生成式,因为元组是不可变类型,不可append
#4、生成器表达式
# a=(i for i in range(10) if i>3)

#注意:此时a一个值也没有!


with open('db_user.txt',mode='rt',encoding='utf-8') as f:
    #方式一:
    # res = 0
    # for i in f:
    #     res+=len(i)
    # print(res)
    #方式二:
    # size_of_file=[len(i) for i in f]
    # print(size_of_file)
    # res=sum(size_of_file)
    # print(res)
    #方式三:效率最高
    res=sum(len(i) for i in f)
    print(res)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值