上一篇
Python循环遍历的8种方法详解 - 从基础到高级循环技巧
- Python
- 2025-07-18
- 2199
Python循环遍历的8种方法详解
循环是编程中最重要的概念之一,掌握多种循环遍历方法能极大提高Python编程效率。本教程将详细讲解Python中8种常用的循环遍历方法,每种方法都配有实际代码示例。
教程目录
1. for循环 - 最常用的遍历方法
for循环是Python中最常用的循环方式,用于遍历任何可迭代对象(列表、元组、字典、字符串等)。
代码示例:
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 遍历字符串
word = "Python"
for char in word:
print(char)
# 遍历字典
person = {"name": "Alice", "age": 30, "city": "New York"}
for key, value in person.items():
print(f"{key}: {value}")
2. while循环 - 条件循环
while循环在条件为真时重复执行代码块,适合不确定循环次数的场景。
代码示例:
# 基本while循环
count = 0
while count < 5:
print(f"Count is {count}")
count += 1
# 使用break退出循环
while True:
user_input = input("输入 'exit' 退出: ")
if user_input == 'exit':
break
print(f"你输入了: {user_input}")
3. 使用range()函数遍历
range()函数生成数字序列,常用于需要索引的循环遍历。
代码示例:
# 遍历0到4
for i in range(5):
print(i)
# 指定起始和结束值
for i in range(2, 6):
print(i) # 输出2,3,4,5
# 指定步长
for i in range(0, 10, 2):
print(i) # 输出0,2,4,6,8
# 倒序遍历
for i in range(5, 0, -1):
print(i) # 输出5,4,3,2,1
4. 使用enumerate()获取索引
enumerate()函数可以在遍历时同时获取索引和元素值。
代码示例:
fruits = ["apple", "banana", "cherry"]
# 基本用法
for index, fruit in enumerate(fruits):
print(f"索引 {index}: {fruit}")
# 指定起始索引
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
5. 使用zip()并行遍历
zip()函数用于同时遍历多个可迭代对象。
代码示例:
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "London", "Paris"]
# 同时遍历两个列表
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# 同时遍历三个列表
for name, age, city in zip(names, ages, cities):
print(f"{name} is {age} years old and lives in {city}")
# 使用enumerate和zip
for i, (name, age) in enumerate(zip(names, ages)):
print(f"{i}: {name} - {age}")
6. 列表推导式 - 简洁高效
列表推导式提供了一种简洁的方式来创建列表,同时执行循环操作。
代码示例:
# 基本列表推导式
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
# 字典推导式
word = "hello"
char_count = {char: word.count(char) for char in set(word)}
print(char_count) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
# 集合推导式
unique_chars = {char for char in word}
print(unique_chars) # {'h', 'e', 'l', 'o'}
7. 使用map()函数遍历
map()函数将一个函数应用于可迭代对象的每个元素,返回一个迭代器。
代码示例:
# 使用map转换元素 numbers = [1, 2, 3, 4, 5] squared = map(lambda x: x**2, numbers) print(list(squared)) # [1, 4, 9, 16, 25] # 结合lambda函数 names = ["alice", "bob", "charlie"] capitalized = map(lambda name: name.capitalize(), names) print(list(capitalized)) # ['Alice', 'Bob', 'Charlie'] # 多个可迭代对象 a = [1, 2, 3] b = [4, 5, 6] result = map(lambda x, y: x + y, a, b) print(list(result)) # [5, 7, 9]
8. 使用filter()函数过滤遍历
filter()函数根据指定函数的返回值过滤可迭代对象中的元素。
代码示例:
# 过滤偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # [2, 4, 6, 8, 10]
# 过滤非空字符串
words = ["hello", "", "world", " ", "python", None]
non_empty = filter(None, words) # None过滤掉False值
print(list(non_empty)) # ['hello', 'world', 'python']
# 使用自定义函数
def is_positive(num):
return num > 0
mixed = [-5, 10, 0, -3.2, 8, 4.5]
positives = filter(is_positive, mixed)
print(list(positives)) # [10, 8, 4.5]
总结:Python循环方法选择指南
根据不同的场景选择合适的循环遍历方法:
- 遍历序列元素:for循环
- 需要索引:enumerate()或range(len())
- 同时遍历多个序列:zip()
- 根据条件循环:while循环
- 创建新列表:列表推导式
- 数据转换:map()函数
- 数据过滤:filter()函数
掌握这些循环遍历方法,将大大提高你的Python编程效率和代码可读性。
本文由DengPan于2025-07-18发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://www.521pj.cn/20255859.html
发表评论