Advanced operations for taking elements from slices of list tuples

In Python, the slicing operation allows you to obtain a subsequence from a sequence (such as a list, tuple, string, etc.) instead of the entire sequence. Slicing operations use colons (:) to specify the starting position, ending position, and step size.

The basic syntax for slicing is:

sequence[start:stop:step]
  • start: The index of the starting position (including the element at that position).
  • stop: The index of the end position (excluding the element at that position).
  • step: Step size, controls the interval of taking elements each time, the default value is 1.

Here are some common slicing operations:

  1. Get subsequence :
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
subset = my_list[2:5]  # 从索引2开始到索引5(不包括),结果为 [2, 3, 4]
  1. Specify step size :
my_string = "abcdefg"
subset = my_string[1:6:2]  # 从索引1开始到索引6(不包括),步长为2,结果为 "bdf"
  1. Omit the start or end position :
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
subset1 = my_list[:5]  # 从开头到索引5(不包括),结果为 [0, 1, 2, 3, 4]
subset2 = my_list[5:]  # 从索引5开始到结尾,结果为 [5, 6, 7, 8, 9]
  1. Reverse slicing :
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
subset = my_list[::-1]  # 从结尾到开头,步长为-1,实现反向,结果为 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
  1. Modify elements in a slice :
my_list = [0, 1, 2, 3, 4, 5]
my_list[1:3] = [10, 20, 30]  # 替换索引1到索引3(不包括)的元素,结果为 [0, 10, 20, 30, 3, 4, 5]

It should be noted that the slicing operation returns a new sequence, and the original sequence has not been changed.

Classic operations in slicing

  • Forward slice to get elements
  • Reverse slice to get elements
  • Specify the step size to take elements

The meaning of slicing operation

Reduce the use of loops in your code

Guess you like

Origin blog.csdn.net/weixin_44943389/article/details/133014334