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
>>>