赞
踩
除了直接相加(生成新的list),还有两种方法(修改其中一个list):
用list的extend方法,L1.extend(L2),该方法将参数L2的全部元素添加到L1的尾部,例如:
>>> L1 = [1, 2, 3, 4, 5] >>> L2 = [20, 30, 40] >>> L1.extend(L2) >>> L1 [1, 2, 3, 4, 5, 20, 30, 40]
用切片(slice)操作,L1[len(L1):len(L1)] = L2和上面的方法等价,例如:
>>> L1 = [1, 2, 3, 4, 5] >>> L2 = [20, 30, 40] >>> L1[len(L1):len(L1)] = L2 >>> >>> L1 [1, 2, 3, 4, 5, 20, 30, 40]
但切片方法用起来更灵活,可以插入到头部,或其他任意部位,例如:
加到开头:
>>> L1 = [1, 2, 3, 4, 5] >>> L2 = [20, 30, 40] >>> L1[0:0] = L2 >>> L1 [20, 30, 40, 1, 2, 3, 4, 5]
加到中间:
>>> L1 = [1, 2, 3, 4, 5] >>> L2 = [20, 30, 40] >>> >>> L1[1:1] = L2 >>> L1 [1, 20, 30, 40, 2, 3, 4, 5]
参考
1.《python libarary referece》5.6.4. Mutable Sequence Types:
(oschina文档镜像地址)http://tool.oschina.net/uploads/apidocs/python2.7.3/library/stdtypes.html#mutable-sequence-types
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。