在 Python 中,for
循环是一种常用的迭代结构,用于遍历序列(如列表、元组、字典、集合、字符串等)中的项目。下面是一些基本的使用方法:
基本用法
最简单的 for
循环形式如下:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
AI 代码解读
这段代码会输出:
apple
banana
cherry
AI 代码解读
使用 range() 函数
如果你需要一个基于数字的循环,可以使用 range()
函数:
for i in range(5):
print(i)
AI 代码解读
这将输出从 0 到 4 的数字:
0 1 2 3 4
AI 代码解读
遍历两个或多个序列
你可以同时遍历两个或更多的序列:
for x, y in [(1, "one"), (2, "two"), (3, "three")]:
print(x, y)
AI 代码解读
输出:
1 one
2 two
3 three
AI 代码解读
使用 else 子句
for
循环还可以有一个可选的 else
子句。当 for
循环正常结束(即没有被 break
语句中断)后执行 else
子句中的代码:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# 循环被中断时不会执行 else 子句
print(n, 'is a prime number')
AI 代码解读
遍历字典
遍历字典时,默认情况下遍历的是键:
d = {
'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
AI 代码解读
如果要同时获取键和值,可以使用 items()
方法:
for key, value in d.items():
print(key, 'corresponds to', value)
AI 代码解读
以上就是 Python 中 for
循环的一些基本用法。当然,还有很多高级用法,比如嵌套循环、使用枚举函数等。