文章目录
- 前言
- 一、遍历序列类型
-
- [1. 遍历字符串](#1. 遍历字符串)
- [2. 遍历列表](#2. 遍历列表)
- [3. 遍历元组](#3. 遍历元组)
- 二、遍历字典
-
- [1. 基本遍历方式](#1. 基本遍历方式)
- [2. 字典遍历的实用技巧](#2. 字典遍历的实用技巧)
- 三、range()函数的使用
-
- [1. range()的基本用法](#1. range()的基本用法)
- [2. range()的实际应用](#2. range()的实际应用)
- [3. range()的进阶用法](#3. range()的进阶用法)
- 四、循环控制语句
-
- [1. break语句](#1. break语句)
- [2. continue语句](#2. continue语句)
- [3. break和continue结合使用](#3. break和continue结合使用)
前言
本文主要介绍遍历序列类型、遍历字典、range()函数的使用和循环控制语句等知识点。
一、遍历序列类型
1. 遍历字符串
python
python
# 遍历字符串中的每个字符
text = "Python"
# 基本遍历
for char in text:
print(char)
# 输出:P y t h o n(每个字符占一行)
# 同时获取索引和字符
for index, char in enumerate(text):
print(f"索引 {index}: 字符 '{char}'")
# 输出:
# 索引 0: 字符 'P'
# 索引 1: 字符 'y'
# 索引 2: 字符 't'
# ...
# 统计字符串中的元音字母
text = "Hello World"
vowels = "aeiouAEIOU"
vowel_count = 0
for char in text:
if char in vowels:
vowel_count += 1
print(f"找到元音: {char}")
print(f"总共找到 {vowel_count} 个元音字母")
2. 遍历列表
python
python
# 基本遍历
fruits = ["apple", "banana", "orange", "grape"]
print("水果列表:")
for fruit in fruits:
print(f"- {fruit}")
# 使用enumerate获取索引和值
print("\n带索引的水果列表:")
for i, fruit in enumerate(fruits):
print(f"{i+1}. {fruit}")
# 修改列表元素
numbers = [1, 2, 3, 4, 5]
print("\n原列表:", numbers)
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2 # 每个元素乘以2
print("修改后:", numbers) # [2, 4, 6, 8, 10]
# 处理嵌套列表
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("\n矩阵遍历:")
for row in matrix:
for element in row:
print(element, end=" ")
print() # 换行
# 输出:
# 1 2 3
# 4 5 6
# 7 8 9
3. 遍历元组
python
python
# 元组遍历与列表类似
coordinates = ((0, 0), (1, 2), (3, 4), (5, 6))
print("坐标点:")
for point in coordinates:
print(f"({point[0]}, {point[1]})")
# 元组解包遍历
print("\n解包遍历:")
for x, y in coordinates:
print(f"x={x}, y={y}")
# 多个序列同时遍历(使用zip)
names = ("Alice", "Bob", "Charlie")
ages = (25, 30, 35)
print("\n姓名和年龄:")
for name, age in zip(names, ages):
print(f"{name}: {age}岁")
二、遍历字典
1. 基本遍历方式
python
python
student = {
"name": "张三",
"age": 18,
"grade": "高三",
"scores": {"数学": 90, "语文": 85, "英语": 92}
}
# 1. 遍历键(默认方式)
print("键的遍历:")
for key in student:
print(key)
# 等价于:for key in student.keys():
# 2. 遍历值
print("\n值的遍历:")
for value in student.values():
print(value)
# 3. 遍历键值对(最常用)
print("\n键值对遍历:")
for key, value in student.items():
print(f"{key}: {value}")
# 4. 使用enumerate获取序号
print("\n带序号的遍历:")
for i, (key, value) in enumerate(student.items()):
print(f"{i+1}. {key} = {value}")
2. 字典遍历的实用技巧
python
python
# 示例:统计单词频率
text = "apple banana apple orange banana apple mango"
words = text.split()
word_count = {}
for word in words:
# 如果单词已存在,计数+1;否则初始化为1
word_count[word] = word_count.get(word, 0) + 1
print("单词频率统计:")
for word, count in word_count.items():
print(f"{word}: {count}次")
# 示例:筛选字典内容
inventory = {
"apple": {"price": 5.0, "quantity": 100},
"banana": {"price": 3.0, "quantity": 50},
"orange": {"price": 4.0, "quantity": 0},
"grape": {"price": 8.0, "quantity": 20}
}
print("\n库存充足的商品:")
for item, details in inventory.items():
if details["quantity"] > 0:
print(f"{item}: {details['quantity']}个,单价{details['price']}元")
# 示例:字典推导式与遍历结合
scores = {"Math": 90, "English": 85, "Science": 88, "History": 78}
# 找出分数大于85的科目
high_scores = {subject: score for subject, score in scores.items() if score > 85}
print("\n高分科目:", high_scores)
三、range()函数的使用
range()函数生成一个整数序列,常用于控制循环次数。
1. range()的基本用法
python
python
# 1. range(stop) - 从0到stop-1
print("range(5):")
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
# 2. range(start, stop) - 从start到stop-1
print("\n\nrange(2, 7):")
for i in range(2, 7):
print(i, end=" ") # 2 3 4 5 6
# 3. range(start, stop, step) - 从start到stop-1,步长为step
print("\n\nrange(1, 10, 2):")
for i in range(1, 10, 2):
print(i, end=" ") # 1 3 5 7 9
print("\n\nrange(10, 0, -1):")
for i in range(10, 0, -1):
print(i, end=" ") # 10 9 8 7 6 5 4 3 2 1
2. range()的实际应用
python
python
# 1. 生成序列并转换为列表
numbers = list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = list(range(0, 20, 2)) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
print("偶数列表:", even_numbers)
# 2. 计算累加和
total = 0
for i in range(1, 101): # 1到100
total += i
print(f"1到100的和:{total}") # 5050
# 3. 生成乘法表
print("\n九九乘法表:")
for i in range(1, 10): # 1-9
for j in range(1, i+1): # 1-i
print(f"{j}×{i}={i*j:2}", end=" ")
print() # 换行
# 4. 列表索引遍历(常用模式)
fruits = ["apple", "banana", "orange", "grape", "mango"]
print("\n列表索引遍历:")
for i in range(len(fruits)):
print(f"索引 {i}: {fruits[i]}")
# 更Pythonic的方式(使用enumerate)
print("\n使用enumerate:")
for i, fruit in enumerate(fruits):
print(f"索引 {i}: {fruit}")
3. range()的进阶用法
python
python
# 1. 生成特定范围的浮点数
# range()不支持浮点数,但可以模拟
start = 0.0
stop = 1.0
step = 0.1
float_range = []
current = start
while current < stop:
float_range.append(round(current, 1))
current += step
print("浮点数范围:", float_range)
# 或者使用numpy的arange(需要安装numpy)
# import numpy as np
# float_range = np.arange(0.0, 1.0, 0.1)
# 2. 生成日期范围(使用datetime)
from datetime import datetime, timedelta
start_date = datetime(2023, 1, 1)
end_date = datetime(2023, 1, 10)
print("\n日期范围:")
for i in range((end_date - start_date).days + 1):
current_date = start_date + timedelta(days=i)
print(current_date.strftime("%Y-%m-%d"))
# 3. 倒序遍历列表
numbers = [10, 20, 30, 40, 50]
print("\n倒序遍历列表:")
for i in range(len(numbers)-1, -1, -1):
print(f"索引 {i}: {numbers[i]}")
# 更简单的方式:使用reversed()
print("\n使用reversed():")
for num in reversed(numbers):
print(num)
四、循环控制语句
1. break语句
break用于完全终止循环,跳出循环体。
python
python
# 示例1:找到第一个满足条件的元素
numbers = [23, 45, 12, 67, 89, 34, 56]
target = 67
print("查找数字 67:")
for num in numbers:
print(f"检查: {num}")
if num == target:
print(f"找到了!")
break # 找到后立即停止循环
else:
print("未找到") # 如果循环正常结束(没被break中断)则执行
# 示例2:用户登录尝试限制
max_attempts = 3
correct_password = "123456"
for attempt in range(1, max_attempts + 1):
password = input(f"第{attempt}次尝试,请输入密码:")
if password == correct_password:
print("登录成功!")
break # 密码正确,跳出循环
print(f"密码错误,还剩{max_attempts - attempt}次机会")
else:
# 循环正常结束(所有尝试都失败)
print("密码错误次数过多,账户已锁定!")
# 示例3:嵌套循环中的break
print("\n搜索二维列表:")
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
target = 5
found = False
for i, row in enumerate(matrix):
for j, value in enumerate(row):
print(f"检查 matrix[{i}][{j}] = {value}")
if value == target:
print(f"找到 {target} 在位置 ({i}, {j})")
found = True
break # 只跳出内层循环
if found:
break # 跳出外层循环
2. continue语句
continue用于跳过当前循环的剩余语句,直接进入下一次循环。
python
python
# 示例1:跳过特定元素
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("1-10中的奇数:")
for num in numbers:
if num % 2 == 0: # 如果是偶数
continue # 跳过偶数,不执行下面的print
print(num, end=" ") # 只打印奇数
# 输出:1 3 5 7 9
# 示例2:处理有效数据
user_inputs = ["123", "abc", "45.6", "78", "xyz", "100"]
print("\n处理数字输入:")
total = 0
for value in user_inputs:
if not value.isdigit(): # 如果不是纯数字
print(f"跳过非数字: '{value}'")
continue
# 只有数字才执行到这里
num = int(value)
total += num
print(f"添加数字: {num}")
print(f"数字总和: {total}")
# 示例3:复杂条件跳过
students = [
{"name": "Alice", "score": 85, "attendance": 0.9},
{"name": "Bob", "score": 45, "attendance": 0.8},
{"name": "Charlie", "score": 92, "attendance": 0.6}, # 出勤率低
{"name": "David", "score": 78, "attendance": 0.95},
{"name": "Eve", "score": 88, "attendance": 0.7} # 出勤率低
]
print("\n合格学生名单:")
for student in students:
# 跳过不及格的学生
if student["score"] < 60:
continue
# 跳过出勤率低于70%的学生
if student["attendance"] < 0.7:
continue
# 只处理合格的学生
print(f"- {student['name']}: 分数{student['score']}, 出勤率{student['attendance']*100}%")
3. break和continue结合使用
python
python
# 示例:学生成绩处理系统
students = [
{"name": "Alice", "scores": [85, 90, 78]},
{"name": "Bob", "scores": [60, 55, 65]}, # 有不及格
{"name": "Charlie", "scores": [92, 95, 90]},
{"name": "David", "scores": [45, 50, 40]}, # 多门不及格
{"name": "Eve", "scores": [88, 85, 90]}
]
print("优秀学生检查:")
for student in students:
print(f"\n检查 {student['name']} 的成绩: {student['scores']}")
# 检查是否有不及格科目
has_failed = False
for score in student["scores"]:
if score < 60:
print(f" 发现不及格科目: {score}")
has_failed = True
break # 发现一个不及格就跳出内层循环
# 如果有不及格,跳过该学生
if has_failed:
print(f" {student['name']} 有不及格科目,跳过")
continue
# 计算平均分
avg_score = sum(student["scores"]) / len(student["scores"])
# 检查是否优秀(平均分>=85)
if avg_score >= 85:
print(f" {student['name']} 是优秀学生,平均分: {avg_score:.1f}")
else:
print(f" {student['name']} 成绩良好,平均分: {avg_score:.1f}")