本文目录导读:

我来介绍Python元组遍历的几种常见方法和案例。
基础遍历方法
直接遍历元素
# 基本元组
fruits = ('apple', 'banana', 'orange', 'grape')
# 直接遍历元素
for fruit in fruits:
print(fruit)
# 输出: apple, banana, orange, grape
使用索引遍历
# 使用range和len
for i in range(len(fruits)):
print(f"索引{i}: {fruits[i]}")
# 输出: 索引0: apple, 索引1: banana, ...
# 使用enumerate同时获取索引和值
for index, fruit in enumerate(fruits):
print(f"位置{index}: {fruit}")
实际应用案例
案例1:学生成绩处理
# 存储学生姓名和成绩的元组列表
students = [
('张三', 85, '数学'),
('李四', 92, '英语'),
('王五', 78, '物理'),
('赵六', 95, '化学')
]
print("=== 学生成绩表 ===")
for student in students:
name, score, subject = student # 元组解包
print(f"{name}的{subject}成绩: {score}")
# 使用enumerate添加序号
for i, (name, score, subject) in enumerate(students, 1):
print(f"{i}. {name} - {subject}: {score}")
案例2:坐标数据处理
# 存储坐标点的元组
points = [
(10.5, 20.3),
(15.2, 25.7),
(8.9, 30.1),
(22.4, 18.6)
]
# 计算所有点到原点的距离
print("=== 坐标点距离计算 ===")
for x, y in points:
distance = (x**2 + y**2) ** 0.5
print(f"点({x}, {y}) 到原点距离: {distance:.2f}")
# 找最远点
max_distance = 0
farthest_point = None
for x, y in points:
distance = (x**2 + y**2) ** 0.5
if distance > max_distance:
max_distance = distance
farthest_point = (x, y)
print(f"最远点: {farthest_point}, 距离: {max_distance:.2f}")
案例3:字典键值对遍历
# 字典的items()返回元组
person = {
'name': '小明',
'age': 25,
'city': '北京',
'job': '工程师'
}
print("=== 个人信息 ===")
for key, value in person.items():
print(f"{key}: {value}")
# 条件筛选
print("\n=== 重要信息 ===")
important_keys = ['name', 'job']
for key, value in person.items():
if key in important_keys:
print(f"【重要】{key}: {value}")
进阶遍历技巧
嵌套元组遍历
# 二维元组(矩阵)
matrix = (
(1, 2, 3),
(4, 5, 6),
(7, 8, 9)
)
print("=== 矩阵遍历 ===")
for row in matrix:
for element in row:
print(element, end=' ')
print() # 换行
# 带行列索引
for i, row in enumerate(matrix):
for j, value in enumerate(row):
print(f"[{i}][{j}]={value}", end=' ')
print()
条件筛选和变换
# 混合数据类型的元组
data = ('Python', 3.8, True, [1, 2, 3], ('a', 'b'), 42)
print("=== 数据分类 ===")
strings = []
numbers = []
others = []
for item in data:
if isinstance(item, str):
strings.append(item)
elif isinstance(item, (int, float)):
numbers.append(item)
else:
others.append(item)
print(f"字符串: {strings}")
print(f"数字: {numbers}")
print(f"其他: {others}")
列表推导式遍历元组
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# 筛选偶数
even_numbers = [num for num in numbers if num % 2 == 0]
print(f"偶数: {even_numbers}")
# 变换元素
squared = [num ** 2 for num in numbers]
print(f"平方: {squared}")
# 组合条件
result = [f"{num}是质数" if num > 1 and all(num % i != 0 for i in range(2, int(num**0.5)+1))
else f"{num}是合数" if num > 1
else f"{num}既不是质数也不是合数"
for num in numbers]
print(result)
实用小技巧
同时遍历多个元组
# 使用zip同时遍历多个元组
names = ('小明', '小红', '小华')
ages = (25, 23, 28)
scores = (90, 85, 95)
print("=== 多个元组合并遍历 ===")
for name, age, score in zip(names, ages, scores):
print(f"{name}: 年龄{age}, 成绩{score}")
# 带索引
for i, (name, age) in enumerate(zip(names, ages)):
print(f"{i+1}. {name}: {age}岁")
元组切片遍历
numbers = tuple(range(1, 11)) # (1, 2, 3, ..., 10)
# 每隔一个元素
print("奇数位置:", numbers[::2]) # (1, 3, 5, 7, 9)
print("偶数位置:", numbers[1::2]) # (2, 4, 6, 8, 10)
# 倒序遍历
print("倒序:", numbers[::-1]) # (10, 9, 8, ..., 1)
# 切片遍历
for num in numbers[3:8]:
print(f"切片元素: {num}") # 4, 5, 6, 7, 8
- 直接遍历:适合只需要元素本身
- enumerate遍历:需要索引和元素时使用
- 元组解包:处理结构化数据很方便
- zip函数:同时遍历多个元组
- 列表推导式:简洁的变换和筛选
- 嵌套遍历:处理多维数据
记住元组的不可变性,遍历过程中不能修改元素,但可以创建新结构。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播