with open('tank_test.txt','w',encoding='utf-8') as f: for line in range(500): f.write(f'www{line}aaa'*(line+1)+'\n')# 求文件内容每一行的长度# 方法1:运用列表生成式----缺点:占用内存。res = [len(line) for line in open('tank_test.txt','r',encoding='utf-8')]print(res)# 方法2:生成器表达式----生成器对象,不占用内存随用随取res = (len(line) for line in open('tank_test.txt','r',encoding='utf-8'))print(res) #at 0x02CE1930>
'''面试题: 请写出一下代码的执行结果并解释。'''def multipliers(): return [lambda x, i*x for i in range(4)] # 0, 1, 2, 3 # [func(x): return 0*x, func(x): return 1*x, # func(x): return 2*x, func(x): return 3*x, ]print([m(2) for m in multipliers()]) # [6, 6, 6, 6]# [func(x): return 0*2, func(x): return 1*2,# func(x): return 2*2, func(x): return 3*2, ]# [0, 2, 4, 6]# [6, 6, 6, 6]# 闭包函数的延迟绑定# 在内层函数执行时才会绑定变量idef multipliers2(): list1 = [] for i in range(4): def func(x, i=i): return x * i list1.append(func) return list1print([m(2) for m in multipliers2()]) # [0, 2, 4, 6]# [0, 2, 4, 6]