迭代函数:zip、enumerate,list解析
#encoding:utf-8 """ 并行迭代: zip enumerate 获取元素及下标 list解析 iter """ #zip # 两个长度相同的列表,求对应元素的和 # 原始做法: # 当两个元素长度不一致时,这个程序就会出问题,zip可以避免这个问题 def zip_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 # 改进 length = len(a) if len(a)<len(b) else len(b) for i in range(length): c.append(a[i] + b[i]) return c #zip实现 def zip_test2(): a,b = [1,2,3,4,5],[9,8,7,6,5] c = [] lst = zip(a,b) print lst for x,y in lst: c.append(x+y) return c # zip优化 def zip_test3(): a,b = [1,2,3,4,5],[9,8,7,6,5] return [x+y for x,y in zip(a,b)] #list长度不一,zip获取 def zip_test4(): a= [1,2,3] b=[11,12,13,14,15] return zip(a,b) # 结果:[(1, 11), (2, 12), (3, 13)] # 字典执行zip,key视序列,将序列对应的元素一次组成元组,做一个list的元素 def zip_test5(): s = {'name':'bob'} t = {'language':'python'} return zip(s,t) #结果:[('name', 'language')] # 颠倒字典的key value的例子 # 方法1:for循环 def zip_test6(): myinfor = {"name":"bob","site":"www.google.com","language":"python"} new_infor = {} for k,v in myinfor.items(): new_infor[v] = k return new_infor # 方法2:zip def zip_test7(): myinfor = {"name":"bob","site":"www.google.com","language":"python"} return dict(zip(myinfor.values(),myinfor.keys())) # zip的参数 *iterables def zip_test8(): list1 = [2,4,6,8] list2 = [11,13,15,17] result = zip(list1,list2) print result #[(2, 11), (4, 13), (6, 15), (8, 17)] return zip(*result) #[(2, 4, 6, 8), (11, 13, 15, 17)] # enumerate def enumerate_test(): week = ['monday','sunday','friday'] for i in range(len(week)): print week[i] + " is " +str(i) # enumerate的方式实现 def enumerate_test2(): week = ['monday','sunday','friday'] for i ,m in enumerate(week): print week[i] + " is " +str(i) if __name__ =="__main__": print "-------zip-------" print zip_test() print zip_test2() print zip_test3() print zip_test4() print zip_test5() print zip_test6() print zip_test7() print zip_test8() print "------enumerate----" enumerate_test() enumerate_test2()
结果:
-------zip------- [10, 10, 10, 10, 10] [(1, 9), (2, 8), (3, 7), (4, 6), (5, 5)] [10, 10, 10, 10, 10] [10, 10, 10, 10, 10] [(1, 11), (2, 12), (3, 13)] [('name', 'language')] {'python': 'language', 'bob': 'name', 'www.google.com': 'site'} {'python': 'language', 'bob': 'name', 'www.google.com': 'site'} [(2, 11), (4, 13), (6, 15), (8, 17)] [(2, 4, 6, 8), (11, 13, 15, 17)] ------enumerate---- monday is 0 sunday is 1 friday is 2 monday is 0 sunday is 1 friday is 2