写一个 Python示例,用一个例子来执行元组切片。元组切片有开始位置、结束位置和要跳转的步骤。元组的切片从开始位置开始,一直到结束位置,但不包括结束位置。这个元组切片的语法是
TupleName[starting_position:ending_position:steps]
如果省略起始位置,元组切片从零索引位置开始。同样,如果您跳过 end _ position,切片将转到元组末尾。如果您忘记了开始和结束,元组切片将复制所有元组项。在这个 Python 示例中,numTuple[2:6]在索引位置 2(物理位置是 3)开始元组切片,在 5 结束。
# Tuple Slice
numTuple = (11, 22, 33, 44, 55, 66, 77, 88, 99, 100)
print("Tuple Items = ", numTuple)
slice1 = numTuple[2:6]
print("Tuple Items from 3 to 5 = ", slice1)
slice2 = numTuple[3:]
print("Tuple Items from 4 to End = ", slice2)
slice3 = numTuple[:7]
print("Tuple Items from Start to 6 = ", slice3)
slice4 = numTuple[:]
print("Tuple Items from Start to End = ", slice4)
元组切片中的负值将从右侧开始切片。例如,numTuple[-5:-2]从元组右侧的第五个位置开始切片,并从右侧上升到第二个位置。在最后一个例子中,numTuple[1:7:2]从 1 开始元组切片,在 6 结束,每隔一秒复制一项。
# Tuple Slice
numTuple = (11, 22, 33, 44, 55, 66, 77, 88, 99, 100)
print("Tuple Items = ", numTuple)
slice1 = numTuple[-5:-2]
print("Tuple Items = ", slice1)
slice2 = numTuple[-4:]
print("Last Four Tuple Items = ", slice2)
slice3 = numTuple[:-5]
print("Tuple Items upto 5 = ", slice3)
slice4 = numTuple[1:7:2]
print("Tuple Items from 1 to 7 step 2 = ", slice4)
Tuple Items = (11, 22, 33, 44, 55, 66, 77, 88, 99, 100)
Tuple Items = (66, 77, 88)
Last Four Tuple Items = (77, 88, 99, 100)
Tuple Items upto 5 = (11, 22, 33, 44, 55)
Tuple Items from 1 to 7 step 2 = (22, 44, 66)
# Tuple Slice
strTuple = tuple("Tutotial Gateway")
print("Tuple Items = ", strTuple)
slice1 = strTuple[2:10]
print("Tuple Items from 3 to 9 = ", slice1)
slice2 = strTuple[-4:]
print("Last Four Tuple Items = ", slice2)
slice3 = strTuple[2:12:2]
print("Tuple Items from 3 to 9 step 2 = ", slice3)
slice4 = strTuple[::2]
print("Every second Tuple Item = ", slice4)
Tuple Items = ('T', 'u', 't', 'o', 't', 'i', 'a', 'l', ' ', 'G', 'a', 't', 'e', 'w', 'a', 'y')
Tuple Items from 3 to 9 = ('t', 'o', 't', 'i', 'a', 'l', ' ', 'G')
Last Four Tuple Items = ('e', 'w', 'a', 'y')
Tuple Items from 3 to 9 step 2 = ('t', 't', 'a', ' ', 'a')
Every second Tuple Item = ('T', 't', 't', 'a', ' ', 'a', 'e', 'a')
标签: sublime