本文目录导读:

我来介绍几种Python列表遍历的常用方法,通过案例来说明:
基础for循环(最常用)
# 遍历列表中的每个元素
fruits = ['苹果', '香蕉', '橙子', '葡萄']
for fruit in fruits:
print(f"我喜欢吃{fruit}")
使用索引遍历
# 方法1:使用range()和len()
fruits = ['苹果', '香蕉', '橙子', '葡萄']
for i in range(len(fruits)):
print(f"第{i+1}个水果是:{fruits[i]}")
# 方法2:使用enumerate()(推荐)
for index, fruit in enumerate(fruits):
print(f"索引{index}:{fruit}")
实际应用案例
案例1:学生成绩管理系统
# 遍历学生列表,计算平均分和最高分
students = [
{"name": "小明", "score": 85},
{"name": "小红", "score": 92},
{"name": "小刚", "score": 78},
{"name": "小丽", "score": 95}
]
total_score = 0
max_score = 0
max_student = ""
for student in students:
name = student["name"]
score = student["score"]
total_score += score
print(f"{name}的成绩是:{score}分")
if score > max_score:
max_score = score
max_student = name
average = total_score / len(students)
print(f"\n班级平均分:{average:.1f}分")
print(f"最高分:{max_student},{max_score}分")
案例2:购物车价格计算
# 遍历购物车,计算总价并显示商品信息
cart = [
{"name": "Python编程书", "price": 89.9, "quantity": 2},
{"name": "鼠标", "price": 45.0, "quantity": 1},
{"name": "键盘", "price": 199.0, "quantity": 1}
]
total = 0
print("购物车清单:")
print("-" * 40)
for item in cart:
subtotal = item["price"] * item["quantity"]
total += subtotal
print(f"{item['name']} × {item['quantity']} = ¥{subtotal:.2f}")
print("-" * 40)
print(f"总计:¥{total:.2f}")
案例3:条件过滤遍历
# 筛选特定条件的数据
numbers = [12, 45, 23, 67, 89, 34, 56, 78]
# 找出所有大于50的数
print("大于50的数字:")
for num in numbers:
if num > 50:
print(num, end=" ")
print("\n")
# 找出奇数和偶数
odd_numbers = []
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
else:
odd_numbers.append(num)
print(f"偶数:{even_numbers}")
print(f"奇数:{odd_numbers}")
案例4:嵌套循环遍历
# 遍历二维列表(矩阵)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("矩阵遍历:")
for i, row in enumerate(matrix):
for j, value in enumerate(row):
print(f"matrix[{i}][{j}] = {value}", end=" ")
print() # 换行
# 计算对角线之和
diagonal_sum = 0
for i in range(len(matrix)):
diagonal_sum += matrix[i][i]
print(f"\n对角线之和:{diagonal_sum}")
高级遍历技巧
# 使用zip()同时遍历多个列表
names = ['张三', '李四', '王五']
ages = [25, 30, 35]
cities = ['北京', '上海', '广州']
print("人员信息:")
for name, age, city in zip(names, ages, cities):
print(f"{name},{age}岁,来自{city}")
# 使用reversed()反向遍历
print("\n反向遍历:")
for num in reversed([1, 2, 3, 4, 5]):
print(num, end=" ")
# 使用sorted()排序后遍历
print("\n\n排序后遍历:")
scores = [85, 92, 78, 95, 88]
for score in sorted(scores, reverse=True):
print(score, end=" ")
- 基本遍历:
for item in list - 带索引遍历:
for i, item in enumerate(list) - 条件遍历:在循环中添加if条件判断
- 多列表遍历:使用zip()函数
- 反向遍历:使用reversed()
- 排序遍历:使用sorted()
选择哪种方法取决于你的具体需求,enumerate()是最常用的带索引遍历方式。
版权声明: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直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播