一、三元表达式
1、普通和三元表达式区别:
1.普通的表达式
def func(x,y): if x > y: return x else: return y ? res = func(1,2) print(res)
2、三元表达式
语法格式:条件成立时返回的值 if 条件 else 条件不成立时要返回的值
x = 1 y = 2 ? res = x if x > y else y print(res) egon = 18 alex = 80 ? res = ‘egon‘ if egon < alex else ‘alex‘ print(res)
二、生成式
1、列表生成式
#格式:[expression for item in iterable in condition] #原代码: ? l = [‘alex_dsb‘,‘lxx_dsb‘,‘wxx_dsb‘,‘xxq‘,‘egon_dsb‘] new_l = [] for name in l: if name.endswith(‘dsb‘): new_l.append(name) #改进后: l = [‘egon_is_sb‘,‘egon_is_dsb‘,‘egon_is_superdsb‘,‘xxq‘,‘egon_dsb‘] ? new_l = [name for name in l] # 最基础的列表生成式 new_l = [name for name in l if name.endswith(‘sb‘)] ? print(new_l) ? #操作案例: #把所有小写字母变成大写 l = [‘egon_is_sb‘,‘egon_is_dsb‘,‘egon_is_superdsb‘,‘xxq‘,‘egon_dsb‘] new_l = [name.upper() for name in l ] print(new_l) ? #去掉所有名字的_sb后缀 l = [‘egon_is_sb‘,‘egon_is_sb‘,‘egon_is_superd_sb‘,‘xxq‘,‘egon_sb‘] new_l = [name.replace(‘_sb‘,‘‘) for name in l] print(new_l)
2、字典生成式
keys = [‘name‘,‘age‘,‘gender‘] ? dic = {key:None for key in keys} print(dic) items = [(‘name‘,‘egon‘),(‘age‘,18),(‘gender‘,‘male‘)] ? dict = {k:v for k,v in items if k!=‘gender‘} print(dict)
3、集合生成式
keys = [‘name‘,‘age‘,‘gender‘] set1 = {key for key in keys} print(set1,type(set1))
4、元组生成式(没有元组生成式)
g = (i for i in range(10) if i > 3) print(g,type(g)) # 输出:<generator object <genexpr> at 0x01D63450> <class ‘generator‘>
5、生成器表达式
g = (i for i in range(10) if i > 3) # !!!!!!!强调!!!!!!! # 此时g的内部,一个值都没有 # 只有next的时候,才会产生一个值 ? print(g) print(next(g)) print(next(g)) print(next(g)) print(next(g)) #方式一: with open(r‘内容.txt‘,mode=‘rt‘,encoding=‘UTF-8‘) as f: res = 0 for line in f: res += len(line) print(res) #方式二: with open(r‘内容.txt‘,mode=‘rt‘,encoding=‘UTF-8‘) as f: res = sum([len(line) for line in f]) print(res) #方式三:效率高 with open(r‘内容.txt‘, mode=‘rt‘, encoding=‘UTF-8‘) as f: # g = (len(line) for line in f) # print(g) # res = sum(g) # print(res) # res = sum((len(line) for line in f)) # 上述可以简写为如下格式 res = sum(len(line) for line in f) print(res)
原文地址:https://www.cnblogs.com/dingbei/p/12571202.html
时间: 2024-10-28 11:41:16