首页 > 代码库 > python 学习之 PythonAdvance2
python 学习之 PythonAdvance2
#!/usr/bin/python #coding=utf-8 #循环设计 #范围函数 S = ‘abcdefghijk‘ #a b c d e f g h i j k for i in range(0, len(S), 2):#0 1 2 3 4 5 6 7 8 9 10 11 print S[i] print len(S) #遍历数组 S = ‘abcdefghijk‘ for (index, char) in enumerate(S): print index print char #多个等长的序列 ta = [1, 2, 3] tb = [9, 8, 7] tc = [‘a‘, ‘b‘, ‘c‘] for (a, b, c) in zip(ta, tb, tc): print(a, b, c) #分解聚合 ta = [1,2,3] tb = [9,8,7] # cluster zipped = zip(ta,tb) print (zipped) # decompose na, nb = zip(*zipped) print(na, nb) #循环对象 f = open(‘test.txt‘) f.next() f.next() f.next() f.next() f.next() f.next() f.next() for line in open(‘test.txt‘): print line #生成器 def gen(): a = 100 yield a a = a*8 yield a yield 1000 for i in gen(): print i def gen(): for i in range(4): yield i G = (x for x in range(4)) #表推导 L = [] for x in range(10): L.append(x**2) print L L = [x**2 for x in range(10)] print L #函数对象 #lambda函数 func = lambda x,y: x + y print func(3, 4) def func(x, y): return x + y print func(3, 4) #函数作为参数传递 def test(f, a, b): print ‘test‘ print f(a, b) test(func, 3, 5) def U(a, b, c): print ‘U‘ print a(b, c) U(func, 5, 6) #map()函数,map()的功能是将函数对象依次作用于表的每一个元素 re = map((lambda x:x+3),[1, 2, 3, 5, 6]) print re re = map((lambda x,y: x+y),[1,2,3],[6,7,9]) print re #filter()函数,如果函数对象返回的是True,则该次的元素被储存于返回的表中 def func(a): if a > 100: return True else: return False print filter(func, [10, 56, 101, 500]) #reduce()函数,reduce可以累进地将函数作用于各个参数 print reduce((lambda x, y: x + y), [1, 2, 3, 4,9]) #错误处理 re = iter(range(5)) try: for i in range(100): print re.next() except StopIteration: print ‘here is end ‘,i print ‘HaHaHaHa‘ ‘‘‘ re = iter(range(5)) for i in range(100): print re.next() print ‘HaHaHaHa‘ try: print(a*2) except TypeError: print("TypeError") except: print("Not Type Error & Error noted") def test_func(): try: m = 1/0 except NameError: print("Catch NameError in the sub-function") try: test_func() except ZeroDivisionError: print("Catch error in the main program") print ‘Lalala‘ raise StopIteration(‘this is error‘) print ‘Hahaha‘ ‘‘‘ #动态类型 a = 3 a = ‘au‘ print a a = 5 b = a a = a + 2 print a print b L1 = [1, 2, 3] L2 = L1 L1 = 1 print L1, L2 L1 =[1, 2, 3] L2 =L1 L1[0] = 10 print L2 #从动态类型看函数的参数传递 def f(x): x = 100 print x a = 1 f(a) print a def f(x): x[2] = 100 print x a =[1, 2, 3] f(a) print a xl =[1, 3, 5] yl =[9, 12, 13] L = [x**2 for (x,y) in zip(xl, yl) if y > 10] print L #通过参数传递,判断数字、字符串、list、tuple、词典等数据类型是否为可变数据对象 a = 2 b = ‘啊哈‘ c = [1, 2, 3] d = (1, 2, 3) e = {‘tom‘: 11, ‘sam‘: 57, ‘lily‘: 100} def num(x): #数字 x = 100 print x num(a) print a def str(x): #字符串 x = ‘ade‘ print x str(b) print b def list(x): #list x[0] = 100 print x list(c) print c def tuple(x): #tuple x[0] = 100 print x tuple(d) raise StopIteration() print d def dic(x): #词典 x[‘tom‘] = 100 print x dic(e) print e
本文出自 “小陌成长之路” 博客,谢绝转载!
python 学习之 PythonAdvance2
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。