python---slicing

Sequence refers to a type of data container whose content is continuous and ordered and can be indexed using subscripts. Lists, tuples, and strings can all be regarded as sequences.

Sequences support slicing, that is: lists, tuples , and strings all support slicing operations.

Slicing : Take out a subsequence from a sequence. Slicing
syntax : sequence [start subscript: end subscript: step size] [left closed, right open]
means taking out elements from the sequence, starting from the specified position, to the specified The position ends and a new sequence is obtained:

Starting subscript: Indicates where to start. It can be left blank. If left blank, it is regarded as starting from the beginning.
End subscript: (exclusive) indicates where it ends. It can be left blank. If left blank, it is regarded as intercepting to the end.
Step size: means in sequence. The interval of taking elements:
        step size 1 means, taking elements one by one
        means step size 2, skipping 1 element each time
        means step size N, skipping N-1 elements each time
        means taking a negative step size, and reverse Take (note that the starting subscript and ending subscript must also be marked in reverse)

example:

# 正向切片

# 列表切片
my_list = [0, 1, 2, 3, 4, 5, 6]
# result1 = my_list[1:4:1]
result1 = my_list[1:4]  # 步长为1可省略
print(result1)  # [1, 2, 3]

# 元组切片
my_tuple = (0, 1, 2, 3, 4, 5, 6)
result2 = my_tuple[:]
print(result2)  # (0, 1, 2, 3, 4, 5, 6)

# 字符串切片
my_str = "0123456"
result3 = my_str[::2]
print(result3)  # 0246

# 负向切片

# 列表切片
my_list_1 = [0, 1, 2, 3, 4, 5, 6]
result1_1 = my_list_1[::-1]  # 将列表反转了
print(result1_1)  # [6, 5, 4, 3, 2, 1, 0]

# 元组切片
my_tuple_1 = (0, 1, 2, 3, 4, 5, 6)
result2_1 = my_tuple_1[3:1:-1]
print(result2_1)  # (3, 2)

# 字符串切片
my_str_1 = "0123456"
result3_1 = my_str_1[::-2]
print(result3_1)  # 6420

Guess you like

Origin blog.csdn.net/weixin_52053631/article/details/132780023