列表生成器 def f(n): return n*2 a = [f(n) for n in range(10)] a1 = [n*n for n in range(10)] print (a) print (type(a)) 输出结果: [0, 1, 8, 27, 64] [0, 1, 4, 9, 16] <type ‘list‘> ---------------------------------------------------- t = ("123",8) a,b = t #相当于a = t[0],b = [t1] a,b,c = t#报错,赋值个数要与元组个数相同 print (a) print (b) 输出结果: 123 8 ----------------------------------------------------- s = (x*2 for x in range(3)) print (s) 输出结果: <generator object <genexpr> at 0x0255A990> print next(s) # python2 s._next_() print next(s) print next(s) print next(s)#这句会报错 StopIteration,不能超固定范围 输出结果: 0 2 4 ---------------------------------------------------------- s = (x*2 for x in range(3)) for i in s: print (i) 输出结果: 0 2 4 注: 1、for 会自动调用内部的next() 2、for 会判断并且处理StopIteration异常 ----------------------------------------------------------- def foo(): print ("ok") renturn 1 foo() def foo(): print ("ok") yield 1#只要有yield就是一个生成器对象,否则就是一个普通函数 foo()#是一个生成器对象,类似一个做菜厨师 g = foo() print g print next(g)#取到一个1 输出结果: <generator object foo1 at 0x0254A990> ok 1 ------------------------------------------------------------- def foo(): #相当于厨师会做两道菜 print ("ok") yield 1 print ("ok") yield 2 g = foo() print (next(g))#做出的第一道菜,返回1 print (next(g))#做出的第二道菜,返回2 print (next(g))#再继续让厨师做菜就会报错了 输出结果: ok 1 ok1 2 --------------------------------------------- 使用for 循环取值 def foo(): print ("ok") yield 1 print ("ok1") yield 2 for i in foo(): print i 输出结果: ok 1 ok1 2 --------------------------------------------------- for 循环遍历可迭代对象。 什么是可迭代对象?是指拥有iter方法的对方叫可迭代对象 如: #列表 a = [1,2,3] a._iter_() #元组 t = (1,2,3) t._iter_() #字典 d = {"name":"guo"} d._iter_() ---------------------------------------------------------------