12. 序列( 1 ) list >>> a = [1, 2, 3] >>> print a [1, 2, 3] >>> print a[0] 1 >>> a[2] = 10 >>> print a [1, 2, 10] tuple >>> b = (1, 2, 3) >>> print b, b[1] (1, 2, 3) 2 >>> b[1] = 20 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
13. 序列( 2 ) str >>> s = 'abcde' >>> print s abcde >>> print s[1] b >>> s[1] = 'd' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment
14. 序列切片 >>> a = 'abcd' >>> print a[1:3] bc >>> print a[1:] bcd >>> print a[:] abcd >>> print a[:3] abc >>> print a[:-1] abc >>> print a[-2] c 字符串反转 >>> print a[::-1] dcba a b c d 0 1 2 3 -4 -3 -2 -1
15. 字典( 1 ) dict >>> c = {'name': 'smallfish', 'age': 20} >>> print c {'age': 20, 'name': 'smallfish'} >>> print c['name'] smallfish >>> c['name'] = 'chenxiaoyu' >>> print c {'age': 20, 'name': 'chenxiaoyu'} >>> del c['age'] >>> print c {'name': 'chenxiaoyu'} >>> c['address'] = 'China, Jiangsu' >>> print c {'name': 'chenxiaoyu', 'address': 'China, Jiangsu'}
16. 字典( 2 ) 格式化输出 >>> c = {'name': 'smallfish', 'age': 20} >>> print "hello %s, your age is %d" % (c['name'], c['age']) hello smallfish, your age is 20 可以简单一点 >>> print "hello %(name)s, your age is %(age)d" % c hello smallfish, your age is 20
17. 集合 set >>> a = set((1, 2, 3)) >>> b = set((2, 4, 6)) >>> print a set([1, 2, 3]) >>> print a, b set([1, 2, 3]) set([2, 4, 6]) >>> print a & b set([2])v >>> print a | b set([1, 2, 3, 4, 6]) >>> print a ^ b set([1, 3, 4, 6]) 去除某数组内重复数据 a = ['aaa', 'bbb', 'ccc', 'aaa', 'ddd', 'aaa'] >>> list(set(a)) ['aaa', 'bbb', 'ccc', 'ddd']
18. 流程控制 if a == 1: print 'aaa' else : print 'bbb' if b == 1: print '111' elif b == 2: print '222' else : print '000' while a < 10: print a a += 1 for item in (1, 2, 3): print item d = {'name': 'smallfish', 'age': 20} for k in d: print k, d[k] for k, v in d.items(): print k, v 输出 age 20 name smallfish
19. 函数( 1 ) def hello(name): "hello function, name is param" print "hello", name >>> print hello.__doc__ hello function, name is param >>> hello('smallfish') hello smallfish # 给函数参数加默认值 def hello(name='smallfish'): # 同上代码 >>> hello() hello smallfish >>> hello('chenxiaoyu') hello chenxiaoyu
27. 修饰器( 2 ) 测试函数: def hello(n): sum = 0 for i in range(n): sum += I return sum 我们可以这样调用: a = time_wrapper(hello) print a(100) 这个不稀奇,还可以这样写: @time_wrapper def hello(n): … 同上 >>> hello(1000000) hello 0.265000104904
28. 示例代码( 1 ) 交换值 1) tmp = a a = b b = tmp 2) a, b = b, a 判断 key 是否在 dict 中 1) if d.has_key(key): 2) if key in d:
29. 示例代码( 2 ) 数组转字典 name = ["smallfish", "user_a", "user_b"] city = ["hangzhou", "nanjing", "beijing"] print dict(zip(name, city)) {'user_b': 'beijing', 'user_a': 'nanjing', 'smallfish': 'hangzhou'} 还需要两次 for 循环么? 输出文件 with open("d:/1.log") as fp: line = fp.readline() print line