Python技术问询:如何打印变量名而非变量值(含列表场景)
First off, let’s tackle your core question—printing variable names like a and b alongside their values. Here are a few practical methods tailored for a school assignment, starting with the simplest approaches:
Method 1: Use a Dictionary to Link Names to Values
The most straightforward way is to create a dictionary where keys are your variable names (as strings) and values are the actual variables. This makes it easy to access both the name and value in one go:
a = 42 b = "Hello Python" # Map variable names to their values variable_dict = {"a": a, "b": b} # Loop through to print names and values for var_name, var_value in variable_dict.items(): print(f"Variable: {var_name}, Value: {var_value}")
Output:
Variable: a, Value: 42 Variable: b, Value: Hello Python
This method is simple to understand and implement—ideal for school work where clarity matters.
Method 2: Handle Variables in a List
If you need to work with variables stored in a list, just adding the variables to the list won’t preserve their names (since lists hold values, not references to variable names). Instead, store tuples of (name string, variable) in the list:
a = 10 b = 20 c = 30 # List of (variable name, variable value) pairs variable_list = [("a", a), ("b", b), ("c", c)] for var_name, var_value in variable_list: print(f"{var_name} = {var_value}")
Output:
a = 10 b = 20 c = 30
Advanced: Dynamically Retrieve Variable Names (Using inspect)
For more dynamic scenarios (like getting the name of a variable passed to a function), you can use Python’s inspect module to parse the source code. This is a bit more complex, but useful for specific cases:
import inspect def print_var_details(var): # Get the context where the function was called caller_frame = inspect.currentframe().f_back # Check local variables to find a match for the passed value for name, value in caller_frame.f_locals.items(): if value is var: print(f"Variable Name: {name}, Value: {var}") return a = 5 print_var_details(a)
Output:
Variable Name: a, Value: 5
Note: This method isn’t foolproof (it may fail with complex expressions or nested variables), so stick to the dictionary/tuple list methods for most school assignments.
内容的提问来源于stack exchange,提问作者jst kiko

