在 Python 中,循环语句是实现重复操作的重要工具。以下将深入探讨一些高级的应用和技巧:
for 循环的高级用法
遍历字典的键值对
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
print(f'Key: {key}, Value: {value}')
遍历多个序列
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f'{name} is {age} years old.')
while 循环的复杂条件
count = 0
while count < 10 and not (count % 2 == 0 and count % 3 == 0):
print(count)
count += 1
嵌套循环的应用
for i in range(5):
for j in range(i + 1):
print('*', end='')
print()
循环中的 break 和 continue
for num in range(10):
if num == 5:
break # 当 num 为 5 时,退出循环
print(num)
for num in range(10):
if num % 2 == 0:
continue # 跳过偶数
print(num)
利用 enumerate 在循环中获取索引
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f'Index: {index}, Fruit: {fruit}')
结合列表推导式的循环
numbers = [1, 2, 3, 4, 5]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)