Distinguish Python [-x], [-x:], [:], [: -x], [:: - 1], [x :: - 1]

Distinguish Python [-x], [-x:], [:], [: -x], [:: - 1], [x :: - 1]

[-X] represents the inverse of the x-th element of the list

numbers = [1, 2, 3, 4, 5, 6]
print(numbers[-1]) # 倒数第一个元素 6
print(numbers[-2]) # 倒数第二个元素 5

[-X:] x denotes the last slice of the elements constituting the

numbers = [1, 2, 3, 4, 5, 6]
print(numbers[-1:]) # 最后一个元素构成的切片 [6]
print(numbers[-2:]) # 最后两个元素构成的切片 [5, 6]

[:] Represents the entire list (for the replication list)

numbers = [1, 2, 3, 4, 5, 6]
new_numbers = numbers[:]
print(new_numbers) # 完整列表[1,2,3,4,5,6]

[: -X] x denotes the last slice constituting elements except

numbers = [1, 2, 3, 4, 5, 6]
print(numbers[:-1]) # 除了最后一个元素构成的切片 [1, 2, 3, 4, 5]
print(numbers[:-2]) # 除了最后两个元素构成的切片 [1, 2, 3, 4]

[:: --1] represents a list of flip

At the same time [:: - x] can also represent flip divisible by x, and the specific reasons for the reversal of the relevant principles, can refer to my next blog post

numbers = [1, 2, 3, 4, 5, 6]
print(numbers[::-1]) # 列表翻转 [6, 5, 4, 3, 2, 1]

[X :: - 1] represents the inversion beginning of the list element subscript x (note the subscripts x, instead of the x-th element) (flip forward)

numbers = [1, 2, 3, 4, 5, 6]
print(numbers[2::-1]) # 从下标为 2 开始翻转 [3, 2, 1]
print(numbers[3::-1]) # 从下标为 3 开始翻转 [4, 3, 2, 1]

Guess you like

Origin www.cnblogs.com/AlanHe/p/12334757.html