三元表达式
条件成立时的返回值 if 条件 else 条件不成立时的返回值
def max2(x,y): if x > y: return x else: return y print(max2(10,20)) x=10 y=20 res=x if x > y else y print(res)
列表生成式
#输出1~10中每个数字的平方l=[item**2 for item in range(1,11)] print(l)
names=[‘alex‘,‘wxx‘,‘lxx‘] 为列表中每个人名加上SB l=[] for name in names: l.append(name + ‘SB‘) names=lprint(l) 列表生成式写法 names=[name+‘SB‘ for name in names] print(names)
names=[‘alex‘,‘wxx‘,‘egon‘,‘lxx‘,‘zhangmingyan‘]为列表中除了egon外的每个人名加上SB l=[] for name in names: if name != ‘egon‘: l.append(name + ‘SB‘) names=l 列表生成式写法 names=[name+‘SB‘ for name in names if name != ‘egon‘] print(names)
把所有元素大写names=[‘egon‘,‘alex_sb‘,‘wupeiqi‘,‘yuanhao‘] names=[name.upper() for name in names] print(names) 把不以sb结尾的元素的长度以列表输出 names=[‘egon‘,‘alex_sb‘,‘wupeiqi‘,‘yuanhao‘] nums=[len(name) for name in names if not name.endswith(‘sb‘)] print(nums)
字典生成式
s1=‘hello‘ l1=[1,2,3,4,5] res=zip(s1,l1) print(res) #输出的是内存地址 print(list(res)) #打印结果:[(‘h‘, 1), (‘e‘, 2), (‘l‘, 3), (‘l‘, 4), (‘o‘, 5)]
keys=[‘name‘,‘age‘,‘sex‘] values=[‘egon‘,18,‘male‘] res=zip(keys,values) print(list(res)) #[(‘name‘, ‘egon‘), (‘age‘, 18), (‘sex‘, ‘male‘)] print(list(res)) d={} for k,v in zip(keys,values): d[k]=v print(d) #{‘name‘: ‘egon‘, ‘age‘: 18, ‘sex‘: ‘male‘}
字典生成器写法 keys=[‘name‘,‘age‘,‘sex‘] values=[‘egon‘,18,‘male‘] d={k:v for k,v in zip(keys,values)} print(d) #{‘name‘: ‘egon‘, ‘age‘: 18, ‘sex‘: ‘male‘}
info={‘name‘: ‘egon‘, ‘age‘: 18, ‘sex‘: ‘male‘} keys=info.keys() # print(keys) iter_keys=keys.__iter__() values=info.values() # print(values) d={k:v for k,v in zip(keys,values)} print(d)
生成器表达式
with open(‘a.txt‘,encoding=‘utf-8‘) as f: nums=(len(line) for line in f) print(max(nums)) #统计a.txt中最长一行的长度
l=[‘egg%s‘ %i for i in range(100)] print(l) #输出‘egg0‘到‘egg99‘
g=(‘egg%s‘ %i for i in range(1000000000000)) # print(g) print(next(g)) print(next(g)) #next一个出一个
原文地址:https://www.cnblogs.com/chillwave/p/9180544.html
时间: 2024-10-07 13:44:48