python切片原理

#slice has three params[start,stop,step]
'''
if step = 0:
      return error
elif step > 0:
      if start is on the left of the stop,:
            return [start,start+step,...,until stop,not include stop]
      if start is on the right of the stop,including start = stop:
            return []
else step < 0:
      if start is on the right of the stop,:
                  return [start,start+step,...,until stop,not include stop]
      if start is on the left of the stop,including start = stop:
                  return []

the fault value of step is 1
if the start and stop are unkown, then start and stop is depend on +/- of step
index could be -infinite to +infinite, but only -len(list) to len(list)-1 maps to value others map to NONE
for index >= len(list), we consider it is on the right of the list's end, maps to NONE
for index < -len(list), we consider it is on the left of the list's start, maps to NONE
for a five-numbers list,that is:
... -7 -6 -5 -4 -3 -2 -1  NONE
    NONE  0   1  2  3  4  5  6  7
          <-----list----->
e.g. but we consider -7 is at the left of -5
'''
list0 = [i for i in range(10)]
'''
           [ 0  1  2  3  4  5  6  7  8  9]
             0  1  2  3  4  5  6  7  8  9  10  11  ...    +index
... -12 -11 -10-9 -8 -7 -6 -5 -4 -3 -2 -1              -index
'''
list1 = list0[1:5]
list2 = list0[1:-1]
list3 = list0[-8:6]
list4 = list0[-1:-5:-2]
list5 = list0[15::-1]# stop <= -11
list6 = list0[-11:11]
list7 = list0[-13:]#stop >=10
list8 = list0[10:]

print('list1',list1)
print('list2',list2)
print('list3',list3)
print('list4',list4)
print('list5',list5)
print('list6',list6)
print('list7',list7)
print('list8',list8)
'''
results:
list1 [1, 2, 3, 4]
list2 [1, 2, 3, 4, 5, 6, 7, 8]
list3 [2, 3, 4, 5]
list4 [9, 7]
list5 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
list6 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list7 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list8 []
'''

 

上一篇:eclipse svn同步过滤掉某些不需要同步的文件


下一篇:linux12shell编程 -->流程控制之case