python 工具

Python 元组(Tuple)

  • 元组和列表类似,是可以包含任何种类对象的有序集合,通过小括号 () 定义
  • 元组一旦创建,里面的元素不可改变,和字符串类似
  • 语法:变量名 = 元组常量/元组类型变量
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. 访问元组元素(和列表一样)

[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')

2. 元组常用函数

序号 函数 描述
1 max(tuple) 返回元组中元素最大值
2 min(tuple) 返回元组中元素最小值
3 tuple.count(obj) 统计元素obj在元组中出现的次数
4 tuple.index(obj) 从元组中找出元素obj第一个匹配项的索引位置
5 value in tuple 如果value在元组里返回True,否则返回False