(python)数据结构---元组

时间:2023-03-10 04:29:48
(python)数据结构---元组

一、描述

  • 一个有序的元素组成的集合
  • 元组是不可变的线性数据结构

二、元组的相关操作

1、元组元素的访问

  • 索引不可超界,否则抛异常IndexError
  • 支持正负索引
 t = (2, 3)
print(t[0]) 运行结果如下:
2

2、tuple.index(value[, start[, end]])

  • 从指定的区间[start, end],查找指定的值value
  • 找到就返回索引,找不到抛出异常ValueError
  • 时间复杂度:O(n),随着数据规模的增大,效率下降
 t = (2, 3)
print(t.index(3)) 运行结果如下:
1

3、tuple.count(value)

  • 返回列表中匹配value的次数
  • 时间复杂度:O(n),随着数据规模的增大,效率下降
 t = ("a", "a", "b", "c")
print(t.count("a")) 运行结果如下:
2

4、命名元组namedtuple

  • 对元组的每个元素进行命名,然后通过名称来获取其值
 from collections import namedtuple

 student = namedtuple("Student", "name age")
tom = student("tom", 20)
print(tom.name)
print(tom.age) 运行结果如下:
tom
20