()
表示。元素类型不限,支持嵌套。
# 定义元组
t = (1, 2, 3)
print(t[0])
# 单元素元组
t1 = (5,)
# 嵌套元组
t2 = (1, (2, 3), 4)
print(t2[1][0])
t[i]
t[1:3]
for x in t
# 多变量赋值
x, y, z = (1, 2, 3)
# 星号解包
head, *body, tail = (1, 2, 3, 4, 5)
print(head, body, tail) # 1 [2, 3, 4] 5
# 函数多返回值
def min_max(lst):
return min(lst), max(lst)
lo, hi = min_max([3, 1, 4])
print(lo, hi)
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y)
# 类型注解
from typing import Tuple
point: Tuple[int, int] = (3, 4)
t = (1, 2, 3)
print(hash(t))
# 元组可作为dict的key,list不行
d = {(1,2): 'a'}
print(d[(1,2)])
# t[0] = 10 # TypeError
lst = [1,2,3]
t = tuple(lst)
lst2 = list(t)
import sys
print(sys.getsizeof(lst), sys.getsizeof(t))
特性 | tuple | list | set | dict |
---|---|---|---|---|
可变性 | 不可变 | 可变 | 可变 | 可变 |
有序性 | 有序 | 有序 | 无序 | 3.7+有序 |
可哈希 | 是 | 否 | 否 | 否 |
用途 | 只读/键 | 通用 | 去重 | 映射 |
t = (1, 2, 3)
# t[0] = 10 # TypeError: 'tuple' object does not support item assignment
t = ([1,2], 3)
t[0][0] = 99
print(t) # ([99, 2], 3)
nums = [3, 1, 4, 1, 5]
print(sorted(nums)) # 返回新列表
nums.sort(reverse=True)
print(nums) # 原地排序
words = ['apple', 'banana', 'pear', 'grape']
print(sorted(words, key=len)) # 按长度排序
# 排序元组列表
students = [('Alice', 95), ('Bob', 88), ('Tom', 90)]
print(sorted(students, key=lambda x: x[1], reverse=True))
from operator import itemgetter
students = [('Alice', 95), ('Bob', 88), ('Tom', 90)]
print(sorted(students, key=itemgetter(1), reverse=True))
# 按成绩降序,成绩相同按姓名升序
students = [('Alice', 95), ('Bob', 88), ('Tom', 95)]
result = sorted(students, key=lambda x: (-x[1], x[0]))
print(result)
# 分组聚合
grouped = {}
for name, score in students:
grouped.setdefault(score, []).append(name)
print(grouped)
import random, time
lst = [random.randint(0, 100000) for _ in range(10**6)]
start = time.time()
sorted(lst)
print('耗时:', time.time()-start)
d = {('Alice', 'Math'): 95, ('Bob', 'Math'): 88}
print(d[('Alice', 'Math')])
import matplotlib.pyplot as plt
scores = [('Alice', 95), ('Bob', 88), ('Tom', 90)]
names = [x[0] for x in scores]
values = [x[1] for x in scores]
plt.bar(names, values)
plt.show()
# 经纬度坐标存储与排序
gps_points = [(39.9, 116.4), (31.2, 121.5), (22.5, 114.1)]
gps_points.sort(key=lambda x: x[0])
# 复杂数据分组与排名
from collections import defaultdict
scores = [('Alice', 'A', 95), ('Bob', 'B', 88), ('Tom', 'A', 90)]
grouped = defaultdict(list)
for name, cls, score in scores:
grouped[cls].append((name, score))
for cls, items in grouped.items():
print(cls, sorted(items, key=lambda x: -x[1]))
# 单元素元组
x = (5) # int
y = (5,) # tuple
# 嵌套可变对象
t = ([1,2], 3)
t[0][0] = 99
# 排序key类型不一致
# sorted([(1,2), (3,'a')], key=lambda x: x[1]) # TypeError
实现一个系统,支持录入多个学生的多门课程成绩,按不同科目和总分排序,输出排名。
实现一个地理信息管理系统,支持元组存储坐标、排序、查找最近点等功能。
实现一个数据分组和多级排序工具,支持按多个字段分组和排序。
用matplotlib等工具对排序结果进行可视化,并分析不同排序方法的性能。