Python 循環(huán)結構精華五點
在Python編程中,循環(huán)結構是一個非常重要的概念,它允許代碼重復執(zhí)行一段邏輯,直到滿足特定條件為止。掌握循環(huán)結構不僅能夠幫助你處理大量數據,還能簡化代碼邏輯,提高效率。下面,我將詳細講解Python循環(huán)結構的五大精華點,并通過實際代碼示例來展示它們的應用。
1. 基本循環(huán)結構:for 循環(huán)和 while 循環(huán)
(1) for 循環(huán)
for 循環(huán)用于遍歷可迭代對象(如列表、元組、字符串等)中的每一個元素。
# 遍歷列表
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# 輸出結果:
# apple
# banana
# cherry
(2) while 循環(huán)
while 循環(huán)在給定條件為真時重復執(zhí)行代碼塊。
# 使用 while 循環(huán)計算1到10的和
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
2. 循環(huán)控制語句:break 和 continue
(1) break
break 語句用于立即退出循環(huán)。
# 使用 break 退出循環(huán)
for number in range(1, 11):
if number == 5:
break
print(number)
# 輸出結果:
# 1
# 2
# 3
# 4
(2) continue
continue 語句用于跳過當前循環(huán)的剩余部分,并繼續(xù)下一次循環(huán)迭代。
# 使用 continue 跳過特定值
for number in range(1, 11):
if number % 2 == 0:
continue
print(number)
# 輸出結果:
# 1
# 3
# 5
# 7
# 9
3. 嵌套循環(huán)
嵌套循環(huán)是一個循環(huán)內部包含另一個循環(huán)。這在處理二維數據結構(如矩陣)時非常有用。
# 嵌套循環(huán)示例:打印一個5x5的星號矩陣
for i in range(5):
for j in range(5):
print('*', end=' ')
print() # 換行
# 輸出結果:
# * * * * *
# * * * * *
# * * * * *
# * * * * *
# * * * * *
4. 循環(huán)中的 else 子句
for 和 while 循環(huán)可以有一個可選的 else 子句,它在循環(huán)正常結束時執(zhí)行(即不是通過 break 語句退出的)。
# 使用 for 循環(huán)的 else 子句
for number in range(1, 6):
if number == 3:
break
print(number)
else:
print("Loop completed without breaking.")
# 輸出結果:
# 1
# 2
# 使用 while 循環(huán)的 else 子句
count = 0
while count < 5:
count += 1
if count == 3:
break
else:
print("Loop completed without breaking.")
# 沒有輸出,因為循環(huán)通過 break 語句退出了
5. 使用 enumerate 和 zip 在循環(huán)中遍歷
(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
(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.
實戰(zhàn)案例:處理CSV文件
假設我們有一個CSV文件 students.csv,內容如下:
name,age,grade
Alice,25,A
Bob,30,B
Charlie,35,A
我們將使用循環(huán)結構來讀取這個文件,并計算每個年級的平均年齡。
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
在這個案例中,我們首先使用 csv.reader 讀取CSV文件,并使用 for 循環(huán)遍歷每一行。然后,我們將學生的年齡根據年級存儲在字典中。最后,我們使用另一個 for 循環(huán)遍歷字典,計算并打印每個年級的平均年齡。
總結
通過本文,我們詳細探討了Python循環(huán)結構的五大精華點:基本循環(huán)結構、循環(huán)控制語句、嵌套循環(huán)、循環(huán)中的 else 子句,以及使用 enumerate 和 zip 在循環(huán)中遍歷。每個點都通過實際代碼示例進行了展示,并解釋了代碼的工作原理和功能。最后,我們通過一個實戰(zhàn)案例——處理CSV文件并計算每個年級的平均年齡,展示了循環(huán)結構在實際編程中的應用。