Python Cookbook学习记录 ch4_1-5_2013/11/2
4.1 对象拷贝
和C++一样,python也有深拷贝和浅拷贝
前拷贝,如下,虽然生成了一个新的对象,但是对象内部属性和内容依然引用原对象
>>> list_of_lists = [['a'],[1,2],['z',23]] >>> copy_lol= copy.copy(list_of_lists) >>> copy_lol[1].append('boo') >>> print list_of_lists,copy_lol [['a'], [1, 2, 'boo'], ['z', 23]] [['a'], [1, 2, 'boo'], ['z', 23]]
深拷贝 :
>>> list_of_lists = [['a'],[1,2],['z',23]] >>> copy_lol= copy.deepcopy(list_of_lists) >>> copy_lol[1].append('boo') >>> print list_of_lists,copy_lol [['a'], [1, 2], ['z', 23]] [['a'], [1, 2, 'boo'], ['z', 23]]
4.2 通过列表推导构建列表
这个已经很常用了,比如将theoldlist中所有大于5的数值取出来每个值都加上23,并将这些值组成一个列表,可以使用如下方法:
>>> theoldlist = [3,6,9,10,31,3,2,67,313] >>> thenewlist = [x+23 for x in theoldlist if x > 5] >>> print thenewlist [29, 32, 33, 54, 90, 336]
4.3 若列表中某元素存在则返回之
因为列表的有效索引只能在大于等于-len(L)和小于len(L)之间
def list_get(L, i, v=None): if -len(L) <= i < len(L): return L[i] else: return v
如果传入的i都是有效索引,则可以采用如下方法:
def list_get_egfp(L, i, v=None): try: return L[i] except IndexError: return v
4.4 循环访问序列中的元素和索引
内建函数enumerate就是为此而生的,enumerate(list)可用于同时遍历索引和内容
>>> lista = ['a','b','c','d','e'] >>> for index,item in enumerate(lista): print index,item 0 a 1 b 2 c 3 d 4 e
4.5在无需共享引用的条件下创建列表的列表
通过列表乘以一个整数可以得到原列表的多次重复,其实后面的子列表都是对第一个子列表的引用,所以当一个的子列表的值改变了,那么其他子列表的值也改变 了
>>> multi = [[0]*5]*3 >>> print multi [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] >>> multi[0][3] = 'haha' >>> print multi [[0, 0, 0, 'haha', 0], [0, 0, 0, 'haha', 0], [0, 0, 0, 'haha', 0]]
可以通过列表推导的方法来创建多维列表
>>> newlist = [[0]*5 for row in range(3)] >>> print newlist [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] >>> newlist[0][3] = 'haha' >>> print newlist [[0, 0, 0, 'haha', 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
浙公网安备 33010602011771号