Python(七):第六章:条件循环分支 发表于 2025-04-18 更新于 2025-10-05
字数总计: 1.6k 阅读时长: 6分钟 阅读量: 广东
第六章:条件循环分支 条件语句的高级用法 链式比较 Python 支持数学风格的链式比较,使得条件表达式更简洁明了。
1 2 3 4 5 6 7 8 9 10 11 if x > 0 and x < 10 : print ("x在0到10之间" ) if 0 < x < 10 : print ("x在0到10之间" ) if 10 <= x < 20 <= y < 30 : print ("x在10到20之间且y在20到30之间" )
短路逻辑评估 Python 使用短路逻辑评估条件表达式,即一旦表达式的真假已经确定,后续部分不再执行。
1 2 3 4 5 6 7 8 9 if expensive_function() and rare_condition(): do_something() if quick_check() or expensive_operation(): do_something()
条件表达式的嵌套 可以在条件表达式内部嵌套其他条件表达式,创建复杂的决策树。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 result = ( "高分" if score >= 90 else "良好" if score >= 80 else "及格" if score >= 60 else "不及格" ) category = ( "儿童" if age < 12 else "青少年" if age < 18 else "成人" if age < 65 else "老年人" )
模式匹配(Python 3.10+) Python 3.10 引入了结构化模式匹配,类似于其他语言的 switch/case 语句,但功能更强大。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 def analyze_type (data ): match data: case int (): return "整数" case float (): return "浮点数" case str (): return "字符串" case list (): return "列表" case dict (): return "字典" case _: return "其他类型" def process_point (point ): match point: case (0 , 0 ): return "原点" case (0 , y): return f"Y轴上的点 y={y} " case (x, 0 ): return f"X轴上的点 x={x} " case (x, y) if x == y: return f"对角线上的点 ({x} , {y} )" case (x, y): return f"普通点 ({x} , {y} )" class Point : def __init__ (self, x, y ): self .x = x self .y = y def analyze_point (point ): match point: case Point(x=0 , y=0 ): return "原点" case Point(x=0 , y=y): return f"Y轴上的点 y={y} " case Point(x=x, y=0 ): return f"X轴上的点 x={x} " case Point(x=x, y=y) if x == y: return f"对角线上的点 ({x} , {y} )" case Point(): return f"普通点 ({point.x} , {point.y} )"
循环的高级技巧 循环与迭代器协议 理解迭代器协议有助于更高效地编写循环代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class CountDown : def __init__ (self, start ): self .start = start def __iter__ (self ): """ 返回迭代器对象 这个方法使CountDown类的实例成为一个可迭代对象。 当使用for循环遍历该对象时,Python会自动调用这个方法获取迭代器。 返回: self: 返回自身作为迭代器 """ return self def __next__ (self ): """ 获取迭代器中的下一个值 这个方法定义了迭代过程中如何获取下一个元素。 每次调用时,计数器减1并返回减1前的值。 当计数器减到0时,抛出StopIteration异常表示迭代结束。 """ if self .start <= 0 : raise StopIteration current = self .start self .start -= 1 return current for i in CountDown(5 ): print (i)
生成器表达式代替列表推导式 生成器表达式在处理大量数据时更节省内存:
1 2 3 4 5 6 7 8 import syssum_of_squares = sys.getsizeof(sum ([x*x for x in range (1000000 )])) print (f"占用内存: {sum_of_squares} bytes" ) sum_of_squares = sys.getsizeof(sum (x*x for x in range (1000000 ))) print (f"占用内存: {sys.getsizeof(sum_of_squares)} bytes" )
使用 enumerate 获取索引 1 2 3 4 5 6 7 8 fruits = ['apple' , 'banana' , 'cherry' ] for i in range (len (fruits)): print (f"{i + 1 } . {fruits[i]} " ) for i, fruit in enumerate (fruits, 1 ): print (f"{i} . {fruit} " )
并行迭代多个序列 1 2 3 4 5 6 7 names = ['Alice' , 'Bob' , 'Charlie' ] ages = [24 , 32 , 28 ] cities = ['New York' , 'Boston' , 'Chicago' ] for name, age, city in zip (names, ages, cities): print (f"{name} , {age} 岁, 来自{city} " )
流程控制的高级模式 嵌套循环的优化 1 2 3 4 5 6 7 8 9 10 11 12 import itertoolsresults = [] for x in range (3 ): for y in range (3 ): for z in range (3 ): results.append((x, y, z)) results = list (itertools.product(range (3 ), range (3 ), range (3 )))
递归与循环 有些问题使用递归比循环更直观:
通过下列的代码处理思想,对于常见的树结构都能以递归的思想去解决问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 def process_nested_list (nested_list, depth=0 ): result = [] for item in nested_list: if isinstance (item, list ): sub_result = process_nested_list(item, depth + 1 ) result.extend(sub_result) else : result.append((depth, item)) return result data = [1 , [2 , [3 , 4 ], 5 ], 6 ] print (process_nested_list(data))