tuple1 = (1, 2, 3, 'hellow', 'world', [4, 5, 6], ('5', 4))
print(type(tuple1)) # <class 'tuple'>
# 将小括号去掉的效果是一样的,python会自动转换
tuple1 = 1, 2, 3, 'hellow', 'world', [4, 5, 6], ('5', 4)
print(type(tuple1)) # <class 'tuple'>
tuple2 = tuple1
tuple2[1] = 'hello' # 报错
# 创建空元组
tuple3 = ()
tuple3 = tuple()
# 元组中只包含一个元素时,需要在元素后面添加逗号 ',' ,否则括号会被当作运算符使用
tuple4 = ('1', )
print(type(tuple4)) # <class 'tuple'>
tuple4 = ('1')
print(type(tuple4)) # <class 'str'>
[1] 偏移量
tuple1 = ('red', 'green', 'blue', 'yellow', 'white', 'black')
正偏移从字符串开始处计数,从 0 开始
负偏移从字符串结尾处反向计数,从 -1 开始
正偏移 = 负偏移 + 字符串长度
| 正偏移→ |
0 |
1 |
2 |
3 |
4 |
| 元组 |
h |
e |
l |
l |
o |
| 负偏移← |
-5 |
-4 |
-3 |
-2 |
-1 |
[2] 索引
# 索引用于获取特定偏移的元素
# 语法:列表[偏移量]
tuple5 = ['red', 'green', 'blue', 'yellow', 'white', 'black']
tuple5[1] # 'green'
tuple5[-3] # 'yellow'
# 偏移量不能超出列表的范围,-len(list) <= 偏移量 <= len(list) - 1
len(tuple5) #6
list2[6] #报错
list[-7] #报错
[3] 分片
# 分片用于提取子列表
# 语法:列表[头下标:尾下标] 截取范围为[头下标,尾下标-1),包含头下标不包含尾下标
# 头下标省略默认值为0,尾下标省略默认值为列表长度
tuple5 = ('red', 'green', 'blue', 'yellow', 'white', 'black')
tuple5[0:3] # ('red', 'green', 'blue')
tuple5[-4:] # ('blue', 'yellow', 'white', 'black')
tuple5[:-2] # ('red', 'green', 'blue', 'yellow', 'white')
# 第三个索引:步进(可选)
# 语法:列表[头下标:尾下标:步进数] 每隔'步进数'个元素索引一次,默认值为1
tuple5 = ('red', 'green', 'blue', 'yellow', 'white', 'black')
tuple5[::2] # ('red', 'blue', 'white')
# 步进数可以为负数,分片将会从右至左进行
# 且两个边界的意义实际上进行了反转,截取范围变成了[头下标, 尾下标+1)
tuple5[::-1] # ('black', 'white', 'yellow', 'blue', 'green', 'red')
tuple5[4:0:-1] # ('white', 'yellow', 'blue', 'green')