元组
- 概念:
有序的
不可变的
元素集合 - 定义
1. 一个元素 t = (888,) print(type(t), t) 2. 多个元素 # 一般写法 t = ("coder", [6, 8], 5) print(type(t), t) # 不建议使用 t = 3, 6, 8, "xiaoxiong" print(type(t), t) # 內建函数,将一个列表转换为元组 l = [3, 6, 8, 10] change_tuple = tuple(l) print(type(change_tuple), change_tuple) # 元组嵌套 t = (6, 8, ("w", "x")) print(type(t), t) 3. 元组推导式 nums = (1, 2, 3, 4, 5, 6) num_tuple = (num * 2 for num in nums if num >= 5) print(type(num_tuple), num_tuple)
- 操作
- 查
1. 获取单个元素:索引 t = (1, 2, 3, 4, 5) print(t[1]) print(t[-1]) 2. 获取多个元素:切片 t = (1, 3, 5, 7, 9) print(t[0:2]) print(t[::-1])
- 获取
- 获取指定元素个数
""" count(item) """ t = (1, 2, 3, 2, 2) c = t.count(2) print(c) c = t.count(2) print(c)
- 获取指定元素索引
t = (1, 2, 3, 2, 2) idx = t.index(2, 2) print(idx)
- 获取元素个数
t = (1, 2, 3, 2, 2) length = len(t) print(length)
- 获取元素最小值
t = (1, 2, 3, 2, 2) min_num = min(t) print(min_num)
- 获取元素最大值
t = (1, 2, 3, 2, 2) max_num = max(t) print(max_num)
- 获取指定元素个数
- 判定
1. 元素 in 元组 2. 元素 not in 元组 t = (3, 5, 7, 9, 1) print(23 in t) print(7 in t)
- 比较
- cmp
""" Python2.x:针对每个元素,从左到右逐一比较 tuple1 < tuple2:-1 tuple1 == tuple2:0 tuple1 > tuple2:1 """ result = cmp((1, 2, 3), (2, 3, 4)) result = cmp((1, 3, 5), [1, 2, 3]) print(result)
- 运算符
""" Python3.x:针对每个元素,从左到右逐一比较 """ < == > result = (1, 2, 3) < (3, 5, 7) print(result)
- cmp
- 拼接
- 乘法运算
num_tuple = (3, 5, 7) print(num_tuple * 3)
- 加法运算
""" 注意:只能元组类型和元组类型相加 """ t_one = (1, 3, 5) t_two = (2, 4, 6) print(t_one + t_two)
- 乘法运算
- 拆包
a = 66 b = 88 b, a = (a, b) print(a, b)
- 查