Python3中exec()的反向操作是什么?如何打印表达式列表的字符串与求值结果?
If you want to display both the string form of expressions and their computed results, there are two straightforward approaches depending on how you prefer to define your expressions.
Approach 1: Store expressions as strings
This is the most direct method—save your expressions as strings, loop through them, evaluate each with eval(), and print both the expression and its result:
expressions = [ "10 + 25 * 2", "len('Python is awesome')", "round(3.14159 * 2, 2)", "max([4, 12, 7, 21]) - min([4, 12, 7, 21])" ] for expr in expressions: result = eval(expr) print(f"{expr} = {result}")
Running this will output:
10 + 25 * 2 = 60 len('Python is awesome') = 17 round(3.14159 * 2, 2) = 6.28 max([4, 12, 7, 21]) - min([4, 12, 7, 21]) = 17
Approach 2: Use lambdas to avoid string quotes
If you’d rather write actual Python expressions instead of wrapping them in strings, you can wrap each expression in a lambda and use inspect.getsource() to extract the expression text:
import inspect def print_expr_with_result(expr_func): # Extract the expression from the lambda's source code source = inspect.getsource(expr_func).strip() # Clean up the lambda wrapper to get just the expression expr = source.split(':')[-1].strip() # Evaluate and print result = expr_func() print(f"{expr} = {result}") # Usage: wrap each expression in a lambda print_expr_with_result(lambda: 10 + 25 * 2) print_expr_with_result(lambda: len('Python is awesome')) print_expr_with_result(lambda: round(3.14159 * 2, 2)) print_expr_with_result(lambda: max([4, 12, 7, 21]) - min([4, 12, 7, 21]))
This gives the same output as the first approach, but you don’t have to quote your expressions. The only tradeoff is the extra lambda wrapper, which is a small price for readability.
内容的提问来源于stack exchange,提问作者user5960761

