Double陈

三元、列表等其他生成式

# # 三元表达式
# def func(x,y):
# if x>y:
# return x
# else:
# return y
#
# # 用三元表达式
# x=1
# y=2
# res=x if x>y else y
# print(res)
#
# 列表生成式
# l = ["name_zhu", "age_zhu", "pig_zhu", "egon"]
# # 把所有名字去掉后缀
# new_l = [name.split("_")[0] for name in l ]
# print(new_l)
# # 只留下有后缀_zhu的然后都去掉后缀
# new_l = [name.split("_")[0] for name in l if name.endswith("zhu")]
# print(new_l)
# # 把所有小写字母改成大写
# new_l=[name.upper() for name in l]
# # print(new_l)

# 其他生成式
# 字典生成式
# keys=["name","age","time"]
# d={ k:None for k in keys }
# print(d)
# items=[("name","chenhao"),("age",18),("time",2000)]
# d={k:v for k,v in items }
# print(d)
# 集合生成式
# keys = ["name", "age", "time"]
# s={k for k in keys}
# print(s)
# 没有元组生成式,只有生成器表达式
# g=(i for i in range(10) if i>3)
# res=next(g)
# print(res)
#
# 升级需求
# 统计a.txt中的所有字符个数 用到sum()
# with open("a.txt",mode="rt",encoding="utf-8") as f:
# res=sum(len(line) for line in f )
# print(res)

posted on 2021-03-30 17:15  Double陈  阅读(37)  评论(0编辑  收藏  举报

导航