Python访问元组

Python访问元组:

使用索引下标进行访问元组:

# 通过索引下标进行访问
tuple_1 = ('a','b','c','d','e','f','g')
# 输出元组中的第一个值
print(tuple_1[0])
# a

# 输出元组中的第六个值
print(tuple_1[5])
# f

# 输出元组的最后一个元素
print(tuple_1[-1])
# g

通过切片访问元组:

# 使用切片对元组进行输出 [start:end:step] 注:不包含 end 位置
tuple_1 = ('a','b','c',4,5,6,7)
# 输出所有元组的元素
print(tuple_1[::])
# ('a', 'b', 'c', 4, 5, 6, 7)

# 输出元组的第三个元素到第五个元素
print(tuple_1[2:5]) #不包含 end
# ('c', 4, 5)

# 步长可以进行修改
print(tuple_1[2:5:2])
# ('c', 5)

# 将元组倒序输出
print(tuple_1[::-1])
# (7, 6, 5, 4, 'c', 'b', 'a')

2020-02-09

原文地址:https://www.cnblogs.com/hany-postq473111315/p/12287609.html