Python如何避免编写大量重复的print调用?
解决重复print调用的几种实用方案
针对你代码里重复的print调用问题,这里有两种简洁的优化方式:
方案1:自定义合并更新与打印的函数
把变量更新和打印逻辑封装成一个函数,避免重复编写print语句:
def update_and_print(current_val, update_expr): # 执行更新操作,返回新值并打印 local_vars = {"val": current_val} exec(f"val {update_expr}", globals(), local_vars) new_val = local_vars["val"] print(new_val) return new_val # 替换成你的实际初始值 userInput = 10 userInput = update_and_print(userInput, "%= 6") userInput = update_and_print(userInput, "+= userInput") userInput = update_and_print(userInput, "-= 4") userInput = update_and_print(userInput, "+= 1") userInput = update_and_print(userInput, "*= 9.857143") userInput = str(userInput) print(f"<{userInput}>")
这个方法直接复用你的原有更新表达式,不需要改写运算逻辑,上手成本低。
方案2:用操作列表+循环统一处理
把所有变量更新逻辑做成可调用的lambda函数,通过循环批量执行并打印,代码更简洁易维护:
# 替换成你的实际初始值 userInput = 10 # 定义所有操作,每个lambda接收当前值并返回更新后的值 operations = [ lambda x: x % 6, lambda x: x + x, lambda x: x - 4, lambda x: x + 1, lambda x: x * 9.857143, lambda x: f"<{str(x)}>" ] for op in operations: userInput = op(userInput) print(userInput)
这种方式把所有操作集中管理,后续要新增或修改操作,只需要调整operations列表即可,print语句只需要写一次。
内容的提问来源于stack exchange,提问作者throwaway1374826390
相关产品推荐
相关产品推荐

