#Encoding:utf-8"""Parallel iterations: Zip Enumerate get elements and subscript list parsing iter"""#Zip#two the same length of the list, the corresponding element and#Original procedure:#when the length of the two elements is inconsistent, the program will have problems, and zip can avoid this problemdefzip_test (): A, B= [1,2,3,4,5],[9,8,7,6,5] C= [] #For i in range (Len (a)): #C.append (A[i] + b[i]) #return C #Improvedlength = Len (a)ifLen (a) <len (b)ElseLen (b) forIinchRange (length): C.append (A[i]+B[i])returnC#Zip ImplementationdefZip_test2 (): A, B= [1,2,3,4,5],[9,8,7,6,5] C=[] LST=Zip (A, b)PrintLST forX, yinchlst:c.append (x+y)returnC#Zip optimizationdefZip_test3 (): A, B= [1,2,3,4,5],[9,8,7,6,5] return[X+y forX, yinchZip (A, b)]#list length varies, zip getsdefZip_test4 (): a= [A] B=[11,12,13,14,15] returnZip (A, B)#results: [(1, one), (2, a), (3,)]#The dictionary executes the Zip,key view sequence, and the elements of the sequence are made into tuples at once, making a list elementdefZip_test5 (): s= {'name':'Bob'} t= {'language':'python'} returnZip (s,t)#Result: [(' Name ', ' language ')]#An example of a key value upside down dictionary#method 1:for LoopdefZip_test6 (): Myinfor= {"name":"Bob","site":"www.google.com","language":"python"} new_infor= {} forKvinchMyinfor.items (): New_infor[v]=kreturnnew_infor#Method 2:zipdefzip_test7 (): Myinfor= {"name":"Bob","site":"www.google.com","language":"python"} returndict (Zip (myinfor.values (), Myinfor.keys ()))#zip parameter *iterablesdefzip_test8 (): List1= [2,4,6,8] List2= [11,13,15,17] Result=Zip (list1,list2)PrintResult#[(2, one), (4, 6), (8, +)] returnZip (*result)#[(2, 4, 6, 8), (one, All, ())]#Enumeratedefenumerate_test (): Week= ['Monday','Sunday','Friday'] forIinchRange (len (week)):PrintWeek[i] +" is"+Str (i)#enumerate way to achievedefEnumerate_test2 (): Week= ['Monday','Sunday','Friday'] forI, MinchEnumerate (week):PrintWeek[i] +" is"+Str (i)if __name__=="__main__": Print "-------zip-------" Printzip_test ()PrintZip_test2 ()Printzip_test3 ()PrintZip_test4 ()Printzip_test5 ()PrintZip_test6 ()Printzip_test7 ()PrintZip_test8 ()Print "------Enumerate----"enumerate_test () enumerate_test2 ( )
Results:
-------Zip-------[Ten,Ten,Ten,Ten,Ten][(1,9), (2,8), (3,7), (4,6), (5,5)][Ten,Ten,Ten,Ten,Ten][Ten,Ten,Ten,Ten,Ten][(1, One), (2, A), (3, -)][('name','language')]{'python':'language','Bob':'name','www.google.com':'site'}{'python':'language','Bob':'name','www.google.com':'site'}[(2, One), (4, -), (6, the), (8, -)][(2,4,6,8), ( One, -, the, -)]------Enumerate----Monday is0Sunday is1Friday is2Monday is0Sunday is1Friday is2
Iteration function: Zip, enumerate,list parsing