Python slice of misunderstanding and advanced usage

As we all know, we can find by index value (or subscript) sequence types (such as strings, lists, tuples, ...) of a single element, then the element if you want to get an index range of how to do it?

Slice (Slice) is a clipping technique index fragments, by slicing technology, we can be processed very flexible type sequence. Generally speaking, the role is to intercept slice sequence object, however, that there are some errors with the use of advanced usage, are worthy of our attention. Therefore, this article will mainly discuss the content with everyone together, I hope you can learn and earn.

Prior statement, not a proprietary operating sections of the list, but because the list of the most representative, so, this article only lists an example for discussion.

1. Slice the basis of usage

Python list is an extremely important basis and a data structure, I wrote a summary article (see link text at the end) comprehensively studied it. This paper summarizes the basic usage slice in detail, now recap:

Written in the form of slices: [i: i + n: m]; where, i is the index value starting slice may be omitted when the first list; i + n is an end position of the slice, the list can be omitted when the last one; m may not be provided, the default value is 1, 0 is not allowed, and when m is negative, inverted list. Note: These values ​​are greater than the length of the list, it will not be reported out of range.

The basic meaning of slices are: from the i-th bit index sequence, right after take up to n-bit elements, the spacer filtration press m.

  li = [1, 4, 5, 6, 7, 9, 11, 14, 16]
  ​
  # 以下写法都可以表示整个列表,其中 X >= len(li)
  li[0:X] == li[0:] == li[:X] == li[:] == li[::] == li[-X:X] == li[-X:]
  ​
  li[1:5] == [4,5,6,7] # 从1起,取5-1位元素
  li[1:5:2] == [4,6] # 从1起,取5-1位元素,按2间隔过滤
  li[-1:] == [16] # 取倒数第一个元素
  li[-4:-2] == [9, 11] # 从倒数第四起,取-2-(-4)=2位元素
  li[:-2] == li[-len(li):-2] == [1,4,5,6,7,9,11] # 从头开始,取-2-(-len(li))=7位元素
  ​
  # 步长为负数时,列表先翻转,再截取
  li[::-1] == [16,14,11,9,7,6,5,4,1] # 翻转整个列表
  li[::-2] == [16,11,7,5,1] # 翻转整个列表,再按2间隔过滤
  li[:-5:-1] == [16,14,11,9] # 翻转整个列表,取-5-(-len(li))=4位元素
  li[:-5:-3] == [16,9] # 翻转整个列表,取-5-(-len(li))=4位元素,再按3间隔过滤
  ​
  # 切片的步长不可以为0
  li[::0]  # 报错(ValueError: slice step cannot be zero)

Some examples of the above for beginners (even many veteran), it may not be easy to understand. I concluded that two experience: (1) firmly in mind formula [i: i + n: m], when the default value is present, by imagining the formula complement; (2) index is negative in steps of positive, the index is calculated by the reciprocal position; the index is negative and step length is negative, a list of the first flip, then calculate the inverse index.

2, is a pseudo-independent object slice

Slicing operation returns the result is independent of a new sequence. A list, for example, the list or a list of sliced, occupying new memory address.

When the result of slices taken, it is an independent object, and therefore, it can be used for assignment, it may also be used for other delivery values ​​scene. However, only the slice shallow copy, it is a reference to the original copy of the list of elements, so that the element becomes longer when the object is present, the new list will be subject to the original list.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
  li = [1, 2, 3, 4]
  ls = li[::]
  ​
  li == ls # True
  id(li) == id(ls) # False
  li.append(li[2:4]) # [1, 2, 3, 4, [3, 4]]
  ls.extend(ls[2:4]) # [1, 2, 3, 4, 3, 4]
  ​
  # 下例等价于判断li长度是否大于8
  if(li[8:]):
      print("not empty")
  else:
      print("empty")
  ​
  # 切片列表受制于原列表
  lo = [1,[1,1],2,3]
  lp = lo[:2] # [1, [1, 1]]
  lo[1].append(1) # [1, [1, 1, 1], 2, 3]
  lp # [1, [1, 1, 1]]

Since the visible, the sections were removed result, it can be used as an independent object, but also pay attention to whether the object taken out of the variable-length element.

3, the slice can be used as a placeholder

Slice either as an independent object is "taken out" of the original sequence and to be left in the original sequence, used as a placeholder.

For the list, using slice as a placeholder, the same effect can be achieved splice list. Of particular note is to slice assignment must be iterable.

  li = [1, 2, 3, 4]
  ​
  # 在头部拼接
  li[:0] = [0] # [0, 1, 2, 3, 4]
  # 在末尾拼接
  li[len(li):] = [5,7] # [0, 1, 2, 3, 4, 5, 7]
  # 在中部拼接
  li[6:6] = [6] # [0, 1, 2, 3, 4, 5, 6, 7]
  ​
  # 给切片赋值的必须是可迭代对象
  li[-1:-1] = 6 # (报错,TypeError: can only assign an iterable)
  li[:0] = (9,) #  [9, 0, 1, 2, 3, 4, 5, 6, 7]
  li[:0] = range(3) #  [0, 1, 2, 9, 0, 1, 2, 3, 4, 5, 6, 7]

In the above example, if a slice taken out as an independent object, you will find that they are empty list, i.e., li [: 0] == li [len (li):] == li [6: 6] == [] I will this placeholder called "pure placeholder" pure placeholder assignment, and will not destroy the original elements, spliced ​​only new elements in a specific position in the index. When you delete a pure placeholder, it will not affect the elements in the list.

"Pure placeholder" corresponds to "non-pure placeholder" non-empty list sections operate it (assign and delete), will affect the original list. If pure placeholder list stitching can be achieved, then the non-pure placeholder replacement list can achieve.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''  
  li = [1, 2, 3, 4]
  ​
  # 不同位置的替换
  li[:3] = [7,8,9] # [7, 8, 9, 4]
  li[3:] = [5,6,7] # [7, 8, 9, 5, 6, 7]
  li[2:4] = ['a','b'] # [7, 8, 'a', 'b', 6, 7]
  ​
  # 非等长替换
  li[2:4] = [1,2,3,4] # [7, 8, 1, 2, 3, 4, 6, 7]
  li[2:6] = ['a']  # [7, 8, 'a', 6, 7]
  ​
  # 删除元素
  del li[2:3] # [7, 8, 6, 7]

Slice placeholder can take steps to achieve a continuous span of replacement or deletion effect. It should be noted that this usage is only supported as long as the replacement.

  li = [1, 2, 3, 4, 5, 6]
  ​
  li[::2] = ['a','b','c'] # ['a', 2, 'b', 4, 'c', 6]
  li[::2] = [0]*3 # [0, 2, 0, 4, 0, 6]
  li[::2] = ['w'] # 报错,attempt to assign sequence of size 1 to extended slice of size 3
  ​
  del li[::2] # [2, 4, 6]

4, more thoughts

Are there other programming languages ​​like Python slicing it? What's the difference?

Guess you like

Origin blog.51cto.com/14246112/2446619