range()
函數在 Python 中用于生成一系列的整數,通常用于循環控制。以下是一些使用 range()
函數進行循環控制的技巧:
for i in range(5):
print(i)
輸出:0 1 2 3 4
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, -1, -1):
print(i)
輸出:5 4 3 2 1 0
squares = [x**2 for x in range(5)]
print(squares)
輸出:[0, 1, 4, 9, 16]
range()
函數):for i in range(3):
for j in range(3):
print(f"({i}, {j})", end=" ")
print()
輸出:
(0, 0) (0, 1) (0, 2)
(1, 0) (1, 1) (1, 2)
(2, 0) (2, 1) (2, 2)
enumerate()
函數獲取索引和值:words = ["apple", "banana", "cherry"]
for index, value in enumerate(words):
print(index, value)
輸出:
0 apple
1 banana
2 cherry
zip()
函數同時遍歷多個序列:names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(name, age)
輸出:
Alice 25
Bob 30
Charlie 35
這些技巧可以幫助你更有效地使用 range()
函數進行循環控制。