如何修改Python代码以在Pruefer Code输出中显示对应树变量名(T10、T11、T12、T13)
Got it, let's fix your output formatting so each Pruefer Code gets labeled with its corresponding tree variable name (T10, T11, etc.). The core issue with your original code is that your list T only stores the tree objects themselves—not the human-readable names you assigned to them (like T10). Python doesn't track variable names attached to objects at runtime, so we need to explicitly pair each tree with its name.
Modified Code
Here's an updated version that uses a list of tuples to bind each tree name to its NetworkX tree object:
from matplotlib.pyplot import figure import networkx as nx # Don't forget to import NetworkX if you haven't already # Define each tree along with its name as a tuple tree_with_names = [ ("T10", nx.random_tree(10)), ("T11", nx.random_tree(11)), ("T12", nx.random_tree(12)), ("T13", nx.random_tree(13)) ] # Assume you've defined your drawing options here (e.g., node labels, colors) opts = {"with_labels": True, "node_color": "#a8d1ff"} for name, tree in tree_with_names: # Use an f-string to insert the tree name into your output print(f"The Pruefer Code for - {name} {pruefer_code(tree)}") # Generate the tree visualization as before fig = figure() axis = fig.add_subplot(111) nx.draw(tree, **opts, ax=axis)
How This Works
- Pair Names with Trees: Instead of storing just tree objects, we create tuples where the first element is the tree's name (like "T10") and the second is the tree itself. This lets us access both values during the loop.
- Formatted Output: F-strings (
f"...") make it straightforward to insert the tree name directly into your print statement, producing the exact labeled output you want. - Unchanged Visualization: The tree drawing logic stays identical—we just use the
treevariable from each tuple instead of the originalt.
Alternative: Using a Dictionary
If you prefer, a dictionary works equally well for mapping names to trees:
trees = { "T10": nx.random_tree(10), "T11": nx.random_tree(11), "T12": nx.random_tree(12), "T13": nx.random_tree(13) } for name, tree in trees.items(): print(f"The Pruefer Code for - {name} {pruefer_code(tree)}") # ... visualization code remains the same
Either approach will give you the labeled Pruefer Code output you're aiming for!
内容的提问来源于stack exchange,提问作者cr28

