List parsing and builder expressions in Python
Yun Zhengjie
Copyright Notice: Original works, declined reprint! Otherwise, the legal liability will be investigated.
I. List resolution CASES
1 #! /usr/bin/env python2 #_*_coding:utf-8_*_3 #@author: Yinzhengjie4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%e8%87%aa%e5%8a%a8%e5%8c%96%e8%bf%90%e7%bb%b4%e4%b9%8b% e8%b7%af/5 #Email:[email protected]6 7Old ="Hello"8 #traditional ways to solve the conversion of letters9List_1 = []Ten forIinchOld : Oneres =I.upper () A list_1.append (RES) - Print(list_1) - #List parsing Methods theRes1 = [I.upper () forIinchOld ] - Print(RES1) - -List_2 = [10,20,30,40,50] + #the traditional way to calculate the list element's two-time square -List_new = [] + forIinchlist_2: ARes2 = i * * 2 at list_new.append (res2) - Print(list_new) - #List parsing Methods -Res2 = [i**2 forIinchList_2] - Print(Res2) - inList_3 = [1,31,45, 62,57,21] - #traditional way to take out values greater than 30 and less than 50 in the list toMaxnum = [] + forIinchList_3: - ifI >30 andI<50: the maxnum.append (i) * Print(Maxnum) $ #List parsing MethodsPanax Notoginsengres = [I forIinchList_3ifI > 30 andI<50] - Print(RES)
Two. Generator expressions
1 #! /usr/bin/env python2 #_*_coding:utf-8_*_3 #@author: Yinzhengjie4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%e8%87%aa%e5%8a%a8%e5%8c%96%e8%bf%90%e7%bb%b4%e4%b9%8b% e8%b7%af/5 #Email:[email protected]6 7 8 9g = (i forIinchRange (1,999999999999999999999999999999999))Ten Print(g) One Print(g.__next__())#Note that the __next__ () method of the generator's expression can also call the next function directly yo! Their effect is equivalent. The generator is obviously forcing the list expression to be quick! A Print(Next (g)) - - theL = [i forIinchRange (1,9999999)]#The speed is simply too slow compared to the generator. - Print(l)
Add: Ternary operation expression can be referred to: http://www.cnblogs.com/yinzhengjie/p/8463774.html
List parsing and builder expressions in Python