Python中的遍历方法详解
在Python中,遍历是处理数据的常见操作。Python提供了多种遍历方法,本文将逐一介绍这些方法的特点、适用场景及使用方法。
for循环
for循环是Python中最常用的遍历方法之一,可以遍历任何可迭代对象。
# 遍历列表
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
# 遍历字符串
text = 'hello'
for char in text:
print(char)
# 遍历字典
person = {
'name': 'Tom', 'age': 20}
for key, value in person.items():
print(key, value)
while循环
while循环也可以用于遍历可迭代对象,但相对于for循环来说,它的适用场景比较有限。
# 遍历列表
fruits =