Python 的循环设计用于直接在 iterables(集合)上迭代,而不是操作索引计数器——使其简洁易读。两种循环类型是 for 和 while。
for 循环——直接迭代项目
python
fruit [, , ]:
(fruit)
fruits = [, ]
i ((fruits)):
(fruits[i])
Python 的 for 直接在 elements 本身上迭代——无需手动索引。这比基于索引的循环更简洁,也更不容易出错。
# range — generate numbers
for i in range(5): # 0,1,2,3,4
for i in range(2, 10, 2): # 2,4,6,8 (start, stop, step)
# enumerate — when you DO need the index AND the item
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# zip — iterate multiple sequences in parallel
for name, age in zip(names, ages):
print(f"{name} is {age}")
# dict iteration
for key, value in user.items():
print(key, value)
enumerate(索引 + 项目)和 zip(并行迭代)取代了笨拙的索引操作——改用它们而不是 range(len(...))。
while condition:
do_work()
if done: break # exit the loop
if skip: continue # jump to the next iteration
for item in items:
if item == target:
break
else:
# runs ONLY if the loop completed WITHOUT a break
print("not found")
else 在循环正常完成时运行(没有 break)——对搜索模式很方便。
Python 的迭代模型——直接在项目上循环而不是索引——是编写可读、习惯性代码的核心。
了解正确的工具(需要索引时使用 enumerate、并行迭代时使用 zip、计数时使用 range、字典时使用 .items())让你能够避免容易出错的 range(len(...)) 反模式,这是来自其他语言的初学者经常写的。
干净的迭代是 Pythonic 代码的特征,这些工具在几乎每个程序中都被使用。