Python 循环语句的高级应用与深度探索

在 Python 中,循环语句是实现重复操作的重要工具。本文将深入探讨 Python 循环语句的高级应用。

 

  1. 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.')
  1. while 循环的高级技巧

# 使用条件判断和计数器控制循环
counter = 0
while counter < 5:
    print(counter)
    counter += 1

# 处理循环中的异常
while True:
    try:
        num = int(input("Enter a number: "))
        break
    except ValueError:
        print("Invalid input. Please enter a number.")
  1. 循环中的嵌套与控制

# 嵌套循环实现矩阵乘法
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
result = [[0, 0], [0, 0]]

for i in range(len(matrix1)):
    for j in range(len(matrix2[0])):
        for k in range(len(matrix2)):
            result[i][j] += matrix1[i][k] * matrix2[k][j]

for row in result:
    print(row)
  1. 循环的优化与性能提升

# 使用列表推导式替代简单的循环
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]
print(squared_numbers)

# 在循环中避免不必要的计算
data = [10, 20, 30, 40, 50]
total = 0
min_value = min(data)
for num in data:
    if num > min_value:
        total += num
print(total)

本文转自:https://www.wodianping.com/app/2024-10/45962.html

posted @ 2024-10-06 21:34  我点评开发者社区  阅读(3)  评论(0编辑  收藏  举报