在 Python 中,**tuple(元组)**和 list(列表)一样,支持索引(indexing)来访问其中的元素。元组是有序且不可变的序列。
t = (10, 20, 30, 40)
print(t[0]) # 10
print(t[2]) # 30
print(t[-1]) # 40
print(t[-2]) # 30
如果索引超出范围,会抛出 IndexError:
t[10]
# IndexError: tuple index out of range
如果元组中包含其他元组或列表,可以连续索引:
t = (1, (2, 3), [4, 5])
print(t[1][0]) # 2
print(t[2][1]) # 5
切片不是单个索引,但常用于元组操作
t = (1, 2, 3, 4, 5)
print(t[1:4]) # (2, 3, 4)
print(t[:3]) # (1, 2, 3)
print(t[::2]) # (1, 3, 5)
t = (1)
print(type(t)) # <class 'int'>
t = (1,)
print(type(t)) # <class 'tuple'>
t[0] = 100
# TypeError: 'tuple' object does not support item assignment
如果你愿意,我也可以帮你对比 tuple vs list 的索引差异,或者讲 tuple 为什么比 list 快。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。