Python 循环结构精华五点

开发 后端
本文我将详细讲解Python循环结构的五大精华点,并通过实际代码示例来展示它们的应用。

在Python编程中,循环结构是一个非常重要的概念,它允许代码重复执行一段逻辑,直到满足特定条件为止。掌握循环结构不仅能够帮助你处理大量数据,还能简化代码逻辑,提高效率。下面,我将详细讲解Python循环结构的五大精华点,并通过实际代码示例来展示它们的应用。

1. 基本循环结构:for 循环和 while 循环

(1) for 循环

for 循环用于遍历可迭代对象(如列表、元组、字符串等)中的每一个元素。

# 遍历列表
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

# 输出结果:
# apple
# banana
# cherry
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

(2) while 循环

while 循环在给定条件为真时重复执行代码块。

# 使用 while 循环计算110的和
count = 1
total = 0
while count <= 10:
    total += count
    count += 1
print(f"The sum of numbers from 1 to 10 is: {total}")

# 输出结果:
# The sum of numbers from 1 to 10 is: 55
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

2. 循环控制语句:break 和 continue

(1) break

break 语句用于立即退出循环。

# 使用 break 退出循环
for number in range(1, 11):
    if number == 5:
        break
    print(number)

# 输出结果:
# 1
# 2
# 3
# 4
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

(2) continue

continue 语句用于跳过当前循环的剩余部分,并继续下一次循环迭代。

# 使用 continue 跳过特定值
for number in range(1, 11):
    if number % 2 == 0:
        continue
    print(number)

# 输出结果:
# 1
# 3
# 5
# 7
# 9
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

3. 嵌套循环

嵌套循环是一个循环内部包含另一个循环。这在处理二维数据结构(如矩阵)时非常有用。

# 嵌套循环示例:打印一个5x5的星号矩阵
for i in range(5):
    for j in range(5):
        print('*', end=' ')
    print()  # 换行

# 输出结果:
# * * * * * 
# * * * * * 
# * * * * * 
# * * * * * 
# * * * * * 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

4. 循环中的 else 子句

for 和 while 循环可以有一个可选的 else 子句,它在循环正常结束时执行(即不是通过 break 语句退出的)。

# 使用 for 循环的 else 子句
for number in range(1, 6):
    if number == 3:
        break
    print(number)
else:
    print("Loop completed without breaking.")

# 输出结果:
# 1
# 2

# 使用 while 循环的 else 子句
count = 0
while count < 5:
    count += 1
    if count == 3:
        break
else:
    print("Loop completed without breaking.")

# 没有输出,因为循环通过 break 语句退出了
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

5. 使用 enumerate 和 zip 在循环中遍历

(1) enumerate

enumerate 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标。

# 使用 enumerate 遍历列表并获取索引和值
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

# 输出结果:
# Index 0: apple
# Index 1: banana
# Index 2: cherry
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

(2) zip

zip 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

# 使用 zip 同时遍历两个列表
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old.")

# 输出结果:
# Alice is 25 years old.
# Bob is 30 years old.
# Charlie is 35 years old.
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

实战案例:处理CSV文件

假设我们有一个CSV文件 students.csv,内容如下:

name,age,grade
Alice,25,A
Bob,30,B
Charlie,35,A
  • 1.
  • 2.
  • 3.
  • 4.

我们将使用循环结构来读取这个文件,并计算每个年级的平均年龄。

import csv

# 初始化字典来存储每个年级的学生年龄
grades = {'A': [], 'B': [], 'C': []}

# 读取CSV文件
with open('students.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    next(reader)  # 跳过标题行
    for row in reader:
        name, age, grade = row
        age = int(age)
        grades[grade].append(age)

# 计算每个年级的平均年龄
for grade, ages in grades.items():
    if ages:
        average_age = sum(ages) / len(ages)
        print(f"The average age of students with grade {grade} is {average_age:.2f}")
    else:
        print(f"No students with grade {grade}")

# 输出结果:
# The average age of students with grade A is 30.00
# The average age of students with grade B is 30.00
# No students with grade C
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

在这个案例中,我们首先使用 csv.reader 读取CSV文件,并使用 for 循环遍历每一行。然后,我们将学生的年龄根据年级存储在字典中。最后,我们使用另一个 for 循环遍历字典,计算并打印每个年级的平均年龄。

总结

通过本文,我们详细探讨了Python循环结构的五大精华点:基本循环结构、循环控制语句、嵌套循环、循环中的 else 子句,以及使用 enumerate 和 zip 在循环中遍历。每个点都通过实际代码示例进行了展示,并解释了代码的工作原理和功能。最后,我们通过一个实战案例——处理CSV文件并计算每个年级的平均年龄,展示了循环结构在实际编程中的应用。

责任编辑:赵宁宁 来源: 手把手PythonAI编程
相关推荐

2019-05-09 09:35:17

Spring Boot技术开发

2009-07-09 17:47:40

使用JDBC

2025-02-05 08:00:39

2020-09-18 07:52:46

Itertools库Python语言

2016-09-21 22:31:47

Python作用域

2023-09-26 22:26:15

Python代码

2022-01-17 21:08:54

Python 循环结构

2023-04-28 14:58:10

Python地图循环点

2009-09-28 10:09:09

Linux内核Linux循环链表

2010-09-08 17:15:45

SQL循环结构

2011-03-22 09:05:37

2009-07-20 09:12:54

Ruby on Rai

2013-08-27 14:20:09

游戏应用图标ASO应用商店优化

2012-09-19 11:45:24

桌面云灾难恢复数据隔离

2013-05-27 09:13:23

2024-11-25 12:10:00

Python推荐系统

2021-09-28 10:32:53

循环类型useEffect

2009-12-29 10:24:51

Linux内核循环链表

2010-12-14 09:42:19

2024-04-16 00:00:00

Spring微服务架构
点赞
收藏

51CTO技术栈公众号