egg_list = [] for i in range(6): #列表推导式 egg_list.append('鸡蛋%s'%i) print(egg_list) #结果:['鸡蛋0', '鸡蛋1', '鸡蛋2', '鸡蛋3', '鸡蛋4', '鸡蛋5']
egg_list = ['鸡蛋%s'%i for i in range(5)] #列表推导式 print(egg_list) 列表推导式 print([i for i in range(10)]) #结果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print([i*i for i in range(10)]) #结果:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
生成器表达式
g = (i for i in range(10)) print(g) #结果:<generator object <genexpr> at 0x0221DCC0> for i in g: print(i)
括号不一样,返回的值不一样===生成器表达式几乎不占用内存
g = (i*i for i in range(10)) g.__next__()
各种推导式
[每一个元素或者是与元素相关的操作 for 元素 in 可迭代类型] ----遍历后挨个处理
[满足元素条件相关的操作 for 元素 in 可迭代类型 if 元素相关条件] ----筛选功能
print([i for i in range(30) if i%3==0]) #结果[0, 3, 6, 9, 12, 15, 18, 21, 24, 27] print([i*i for i in range(30) if i%3==0]) #结果[0, 9, 36, 81, 144, 225, 324, 441, 576, 729]
多层嵌套
names = [['Tom','Jack','hdjseej'], ['Jenefer','Cheryol','eeeejjk']] result = [name for lst in names for name in lst if name.count('e')>=2] print(result) #结果:['hdjseej', 'Jenefer', 'eeeejjk']
字典推导式
#1.将key与value对调 dic = {'a':10,'b':20} reverse = {dic[k]: k for k in dic} print(reverse) #结果:{10: 'a', 20: 'b'}
#2.合并大小写所对应的value值,将k统一成小写
dic = {'a':10,'b':20,'A':3,'Z':4}
dic_new = {k.lower():dic.get(k.lower(),0)+dic.get(k.upper(),0) for k in dic}
print(dic_new) #结果:{'a': 13, 'b': 20, 'z': 4}
集合推导式-----结果自动去重
sq = {x*x for x in [1,-1,2]} print(sq) #结果:{1, 4}