遍历序列
Python中的for in
循环是一种用于遍历序列(如列表、元组、字符串、字典、集合等)的核心语法结构。以下是其基本用法及扩展说明:
一、基础语法结构
for 变量 in 可迭代对象:
执行操作
-
可迭代对象 :需包含
__iter__
方法的对象,例如列表、元组、字符串、字典、集合等。 -
循环体 :缩进的代码块,对序列中的每个元素执行一次。
二、常见应用场景
-
遍历列表
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
输出:
apple banana cherry
-
遍历字符串
name = "Python" for letter in name: print(letter)
输出:
P y t h o n
-
遍历字典
-
遍历键 :
person = {"name": "Alice", "age": 25, "city": "New York"} for key in person: print(key, ":", person[key])
输出:
name: Alice age: 25 city: New York
-
遍历键值对 :
for key, value in person.items(): print(key, ":", value)
输出:
name: Alice age: 25 city: New York
-
三、控制循环流程
-
break :提前退出循环
peoples = ['Ralf', 'Clark', 'Leon', 'Terry', 'Mary'] for people in peoples: if people == 'Terry': break print(people)
输出:
Ralf Clark Leon
-
continue :跳过当前迭代,继续下一轮
peoples = ['Ralf', 'Clark', 'Leon', 'Terry', 'Mary'] for people in peoples: if people == 'Leon': continue print(people)
输出:
Ralf Clark Terry Mary
四、扩展功能
-
使用
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
-
遍历字典值
colors = {'red': 1, 'green': 2, 'blue': 3} for color in colors.values(): print(color)
输出:
1 2 3
五、注意事项
-
缩进 :Python依赖缩进来定义代码块,建议使用4个空格或1个Tab键。
-
可迭代对象 :若需遍历自定义对象,需实现
__iter__
和__next__
方法。
通过以上方法,for in
循环可灵活应对不同数据结构的遍历需求,是Python编程的基础工具。