偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

Python 循環(huán)結(jié)構(gòu)精華五點(diǎn)

開發(fā) 后端
本文我將詳細(xì)講解Python循環(huán)結(jié)構(gòu)的五大精華點(diǎn),并通過實(shí)際代碼示例來展示它們的應(yīng)用。

在Python編程中,循環(huán)結(jié)構(gòu)是一個(gè)非常重要的概念,它允許代碼重復(fù)執(zhí)行一段邏輯,直到滿足特定條件為止。掌握循環(huán)結(jié)構(gòu)不僅能夠幫助你處理大量數(shù)據(jù),還能簡化代碼邏輯,提高效率。下面,我將詳細(xì)講解Python循環(huán)結(jié)構(gòu)的五大精華點(diǎn),并通過實(shí)際代碼示例來展示它們的應(yīng)用。

1. 基本循環(huán)結(jié)構(gòu):for 循環(huán)和 while 循環(huán)

(1) for 循環(huán)

for 循環(huán)用于遍歷可迭代對象(如列表、元組、字符串等)中的每一個(gè)元素。

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

# 輸出結(jié)果:
# apple
# banana
# cherry

(2) while 循環(huán)

while 循環(huán)在給定條件為真時(shí)重復(fù)執(zhí)行代碼塊。

# 使用 while 循環(huán)計(jì)算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}")

# 輸出結(jié)果:
# 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)

# 輸出結(jié)果:
# 1
# 2
# 3
# 4

(2) continue

continue 語句用于跳過當(dāng)前循環(huán)的剩余部分,并繼續(xù)下一次循環(huán)迭代。

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

# 輸出結(jié)果:
# 1
# 3
# 5
# 7
# 9

3. 嵌套循環(huán)

嵌套循環(huán)是一個(gè)循環(huán)內(nèi)部包含另一個(gè)循環(huán)。這在處理二維數(shù)據(jù)結(jié)構(gòu)(如矩陣)時(shí)非常有用。

# 嵌套循環(huán)示例:打印一個(gè)5x5的星號矩陣
for i in range(5):
    for j in range(5):
        print('*', end=' ')
    print()  # 換行

# 輸出結(jié)果:
# * * * * * 
# * * * * * 
# * * * * * 
# * * * * * 
# * * * * * 

4. 循環(huán)中的 else 子句

for 和 while 循環(huán)可以有一個(gè)可選的 else 子句,它在循環(huán)正常結(jié)束時(shí)執(zhí)行(即不是通過 break 語句退出的)。

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

# 輸出結(jié)果:
# 1
# 2

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

# 沒有輸出,因?yàn)檠h(huán)通過 break 語句退出了

5. 使用 enumerate 和 zip 在循環(huán)中遍歷

(1) enumerate

enumerate 函數(shù)用于將一個(gè)可遍歷的數(shù)據(jù)對象(如列表、元組或字符串)組合為一個(gè)索引序列,同時(shí)列出數(shù)據(jù)和數(shù)據(jù)下標(biāo)。

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

# 輸出結(jié)果:
# Index 0: apple
# Index 1: banana
# Index 2: cherry

(2) zip

zip 函數(shù)用于將可迭代的對象作為參數(shù),將對象中對應(yīng)的元素打包成一個(gè)個(gè)元組,然后返回由這些元組組成的列表。

# 使用 zip 同時(shí)遍歷兩個(gè)列表
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old.")

# 輸出結(jié)果:
# Alice is 25 years old.
# Bob is 30 years old.
# Charlie is 35 years old.

實(shí)戰(zhàn)案例:處理CSV文件

假設(shè)我們有一個(gè)CSV文件 students.csv,內(nèi)容如下:

name,age,grade
Alice,25,A
Bob,30,B
Charlie,35,A

我們將使用循環(huán)結(jié)構(gòu)來讀取這個(gè)文件,并計(jì)算每個(gè)年級的平均年齡。

import csv

# 初始化字典來存儲每個(gè)年級的學(xué)生年齡
grades = {'A': [], 'B': [], 'C': []}

# 讀取CSV文件
with open('students.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    next(reader)  # 跳過標(biāo)題行
    for row in reader:
        name, age, grade = row
        age = int(age)
        grades[grade].append(age)

# 計(jì)算每個(gè)年級的平均年齡
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}")

# 輸出結(jié)果:
# 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

在這個(gè)案例中,我們首先使用 csv.reader 讀取CSV文件,并使用 for 循環(huán)遍歷每一行。然后,我們將學(xué)生的年齡根據(jù)年級存儲在字典中。最后,我們使用另一個(gè) for 循環(huán)遍歷字典,計(jì)算并打印每個(gè)年級的平均年齡。

總結(jié)

通過本文,我們詳細(xì)探討了Python循環(huán)結(jié)構(gòu)的五大精華點(diǎn):基本循環(huán)結(jié)構(gòu)、循環(huán)控制語句、嵌套循環(huán)、循環(huán)中的 else 子句,以及使用 enumerate 和 zip 在循環(huán)中遍歷。每個(gè)點(diǎn)都通過實(shí)際代碼示例進(jìn)行了展示,并解釋了代碼的工作原理和功能。最后,我們通過一個(gè)實(shí)戰(zhàn)案例——處理CSV文件并計(jì)算每個(gè)年級的平均年齡,展示了循環(huán)結(jié)構(gòu)在實(shí)際編程中的應(yīng)用。

責(zé)任編輯:趙寧寧 來源: 手把手PythonAI編程
相關(guān)推薦

2009-07-09 17:47:40

使用JDBC

2019-05-09 09:35:17

Spring Boot技術(shù)開發(fā)

2025-02-05 08:00:39

2016-09-21 22:31:47

Python作用域

2020-09-18 07:52:46

Itertools庫Python語言

2022-01-17 21:08:54

Python 循環(huán)結(jié)構(gòu)

2023-09-26 22:26:15

Python代碼

2023-04-28 14:58:10

Python地圖循環(huán)點(diǎn)

2012-09-19 11:45:24

桌面云災(zāi)難恢復(fù)數(shù)據(jù)隔離

2013-05-27 09:13:23

2011-03-22 09:05:37

2013-08-27 14:20:09

游戲應(yīng)用圖標(biāo)ASO應(yīng)用商店優(yōu)化

2009-07-20 09:12:54

Ruby on Rai

2021-09-28 10:32:53

循環(huán)類型useEffect

2009-09-28 10:09:09

Linux內(nèi)核Linux循環(huán)鏈表

2010-09-08 17:15:45

SQL循環(huán)結(jié)構(gòu)

2024-11-25 12:10:00

Python推薦系統(tǒng)

2009-06-11 14:30:10

Windows 7微軟操作系統(tǒng)

2024-04-16 00:00:00

Spring微服務(wù)架構(gòu)

2010-12-14 09:42:19

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號