列表切片问题
2018-01-03@望京
关于列表切片的注意事项
>>> a = [1,2,3,4,5] >>> >>> b=a >>> >>> id(a) 140353696988696 >>> id(b) 140353696988696 >>> >>> >>> a is b True >>> >>> >>> b.append(6) >>> >>> a [1, 2, 3, 4, 5, 6] >>> b [1, 2, 3, 4, 5, 6] >>> >>> c = a[3:] >>> >>> id(c) 140353697153824 >>> c [4, 5, 6] >>> >>> d = a[:2] >>> >>> id(d) 140353697153896 >>> d [1, 2] >>> >>> >>> e = a[:] >>> >>> id(e) 140353697154472 >>> id(a) 140353696988696 >>> >>> >>> e [1, 2, 3, 4, 5, 6] >>> >>> >>> import copy >>> f = copy.deepcopy(a) >>> id(f) 140353697153752 >>> id(a) 140353696988696 >>> >>> f [1, 2, 3, 4, 5, 6] >>> >>> >>> a [1, 2, 3, 4, 5, 6] >>> b [1, 2, 3, 4, 5, 6] >>> e [1, 2, 3, 4, 5, 6] >>> f [1, 2, 3, 4, 5, 6] >>> >>> >>> id(a),id(b),id(e),id(f) (140353696988696, 140353696988696, 140353697154472, 140353697153752) >>> >>> >>> a is b True >>> a is e False >>> a is f False >>>
补充示例1
>>> a [1, 2, 3, 4, 5, 6] >>> >>> g = a[-2:] >>> g [5, 6] >>> >>> h = a[1:3] >>> h [2, 3] >>> >>> i = a[3:1] >>> i [] >>> >>> j = a[2:-1] >>> j [3, 4, 5] >>>
用切片来删除序列里的某一段
>>> >>> a = [1, 2, 3, 4, 5, 6, 7] >>> >>> a[1:4] = [] >>> >>> a [1, 5, 6, 7] >>>
列表反转
>>> >>> li = ['a','b','c','d'] >>> li.reverse() >>> li ['d', 'c', 'b', 'a'] >>> print ''.join(li) dcba >>>
关于字符串切片注意事项(不同于列表)
>>> >>> a = 'standby' >>> a 'standby' >>> >>> b = a[:] >>> b 'standby' >>> >>> a is b True >>> >>> id(a) 139908204403952 >>> id(b) 139908204403952 >>> >>>
切片实现字符串反转
>>> >>> a = 'standby' >>> a[::-1] 'ybdnats' >>> >>> >>> a = 'Life is short, use Python.' >>> a[::3] 'Leshtu tn' >>> >>> a[::-2] '.otPeu,rh iei' >>>
递归实现字符串反转
>>> >>> def str_reverse(string): ... if '' == string: ... return string ... else: ... return str_reverse(string[1:])+string[0] ... >>> str_reverse('Use Python.') '.nohtyP esU' >>>
赋值在字符串和列表中的区别 *****
>>> >>> a = 'standby' >>> >>> b = 'standby' >>> >>> a is b True >>> >>> id(a) 139908204403952 >>> id(b) 139908204403952 >>> >>> >>> >>> a = [1,2,3] >>> b = [1,2,3] >>> >>> a is b False >>> >>> id(a) 139908204413800 >>> id(b) 139908204248600 >>>
作者:Standby — 一生热爱名山大川、草原沙漠,还有我们小郭宝贝!
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。