Python的for循环是一种常见的迭代控制结构,除了基本的遍历序列元素的用法,它还有一些更加高级和灵活的用法。下面我们来详细介绍Python for循环的高级用法:
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(i, fruit)
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
for num in range(2, 10):
for i in range(2, num):
if num % i == 0:
print(f"{num} equals {i} * {num//i}")
break
else:
print(f"{num} is a prime number")
# continue: 跳过当前循环,进入下一次循环
# break: 立即退出整个循环
# pass: 什么也不做,用作占位符
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5)) # Output: 120
temperatures = {
'Beijing': [10, 15, 12, 8, 16, 18],
'Shanghai': [14, 17, 15, 12, 20, 22],
'Guangzhou': [22, 24, 23, 21, 26, 25]
}
for city, temps in temperatures.items():
max_temp = max(temps)
min_temp = min(temps)
print(f"In {city}, the highest temperature is {max_temp}°C and the lowest is {min_temp}°C.")
通过掌握Python for循环的高级用法,我们可以编写更加简洁、高效和可读性强的代码,提高编程效率和代码质量。同时,这些高级用法也为我们日常的数据处理和分析工作提供了强大的工具。