三元表达式,列表推倒式,生成器表达式
一. 三元表达式
def max_(a, b): return a if a > b else b print(max_(3,4)) #result 4
二. 列表推导式
#列表推导式形式: [表达式 for 变量 in 可迭代对象] 或者 [表达式 for 变量 in 可迭代对象 if 条件]
#字典推导式形式:
{k:v for循环 if判断}
l = [1,2,3,4,5,6,7,8,9,10] print([x**2 for x in l]) print([x**2 for x in l if x>5]) print(dict([(x,x*2) for x in l])) print([ (x, y) for x in range(10) if x % 2 if x > 3 for y in range(10) if y > 7 if y != 8 ]) a = [2,5,9] b = [4,1,-6] print([a[i] + b[i] for i in range(len(a))]) print("\n".join(("\t".join(["%sx%s=%s"%(x,y,x*y) for y in range(1, x+1)]) for x in range(1,10))))#一行代码打印99乘法表 def mu(i): return i*2 print([mu(i) for i in l])
dic = {"jj": "林俊杰", "jay": "周杰伦", "zs": "赵四", "ln":"刘能"} #字典推导式
d1 = {v:k for k,v in dic.items()}
print(d1)
#结果
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] [36, 49, 64, 81, 100] {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18, 10: 20} [(5, 9), (7, 9), (9, 9)] [6, 6, 3] 1x1=1 2x1=2 2x2=4 3x1=3 3x2=6 3x3=9 4x1=4 4x2=8 4x3=12 4x4=16 5x1=5 5x2=10 5x3=15 5x4=20 5x5=25 6x1=6 6x2=12 6x3=18 6x4=24 6x5=30 6x6=36 7x1=7 7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49 8x1=8 8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64 9x1=9 9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
{'林俊杰': 'jj', '周杰伦': 'jay', '赵四': 'zs', '刘能': 'ln'}
三. 生成器表达式
#列表推导式把[] 换成()就是生成器表达式。 l = [x*x for x in range(10)] g = (x*x for x in range(10)) print(l) print(g) for i in g: print(i)
#result [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] <generator object <genexpr> at 0x101f92f48> 0 1 4 9 16 25 36 49 64 81
#生成器表达式的优点,惰性计算,一次取一个值,节省内存。
四. 声明式编程练习
# 四 声明式编程练习题 # # 1、将names=['egon','alex_sb','wupeiqi','yuanhao']中的名字全部变大写 # names=['egon','alex_sb','wupeiqi','yuanhao'] # new_names = [x.upper() for x in names] # print(new_names) # 2、将names=['egon','alex_sb','wupeiqi','yuanhao']中以sb结尾的名字过滤掉,然后保存剩下的名字长度 # names=['egon','alex_sb','wupeiqi','yuanhao'] # new_names2 = [x for x in names if not x.endswith("sb") ] # print(new_names2) # 3、求文件a.txt中最长的行的长度(长度按字符个数算,需要使用max函数) # with open("a.txt", "r", encoding="utf-8") as f: # print(max((len(i) for i in f))) # 4、求文件a.txt中总共包含的字符个数?思考为何在第一次之后的n次sum求和得到的结果为0?(需要使用sum函数) # with open("a.txt", "r", encoding="utf-8") as f: # print(sum((len(i) for i in f))) #文件句柄中的数据读完了 # 5、思考题 # # with open('a.txt') as f: # g=(len(line) for line in f) # print(sum(g)) #为何报错? #因为生成器是惰性取值的,当print执行的时候f文件句柄已经关闭 # 6、文件shopping.txt内容如下 # # mac,20000,3 # lenovo,3000,10 # tesla,1000000,10 # chicken,200,1 # 求总共花了多少钱? # # 打印出所有商品的信息,格式为[{'name':'xxx','price':333,'count':3},...] # with open("shopping.txt", "r", encoding="utf-8") as f: # print([{"name":x.split(",")[0],"price":x.split(",")[1],"count":x.split(",")[2].strip()} for x in f]) # 求单价大于10000的商品信息,格式同上 # with open("shopping.txt", "r", encoding="utf-8") as f: # print([{"name":x.split(",")[0],"price":x.split(",")[1],"count":x.split(",")[2].strip()} for x in f if int(x.split(",")[1]) > 10000])