Python新手求优化:多条件匹配变量代码的更高效写法
Hey there! As someone who’s been stuck with clunky if-elif chains when starting out in Python, let’s turn your code into something cleaner, more maintainable, and properly Pythonic.
The Problem with Long If-Elif Chains
Your original approach works, but it’s hard to scale—adding a new orbiting body means writing another elif block, and it’s easy to miss typos or make inconsistent changes. Plus, it’s slower to read and debug compared to a more structured approach.
Better Approach: Use a Dictionary for Parameter Mapping
Dictionaries are perfect for this kind of key-value matching. They let you store all your orbiting body parameters in one place, with near-instant lookup times. Here are a few ways to implement this:
Option 1: Tuple-Based Mapping (Simple & Concise)
Great if you remember the order of your parameters and want minimal code:
# Define all body parameters in a single dictionary body_params = { "Ariel": (578.9, 90.099), "Callisto": (2410.3, 7181.224), "Ceres": (481.5, 62.66886), # Add more bodies here as needed } # Clean up user input to handle extra spaces orbiting_body = input("Enter the orbiting body: ").strip() # Retrieve parameters with error handling try: primary_body_radius, gravitational_parameter = body_params[orbiting_body] except KeyError: print(f"Oops! '{orbiting_body}' isn't a recognized orbiting body.") # Set default values or handle the error as needed primary_body_radius = None gravitational_parameter = None
Option 2: Nested Dictionary Mapping (Self-Documenting)
Perfect for readability—anyone looking at the code can immediately see what each value represents:
body_params = { "Ariel": { "primary_body_radius": 578.9, "gravitational_parameter": 90.099 }, "Callisto": { "primary_body_radius": 2410.3, "gravitational_parameter": 7181.224 }, "Ceres": { "primary_body_radius": 481.5, "gravitational_parameter": 62.66886 } } orbiting_body = input("Enter the orbiting body: ").strip() # Use .get() to safely retrieve parameters without try/except params = body_params.get(orbiting_body) if params: primary_body_radius = params["primary_body_radius"] gravitational_parameter = params["gravitational_parameter"] else: print(f"Oops! '{orbiting_body}' isn't a recognized orbiting body.") primary_body_radius = None gravitational_parameter = None
Option 3: Dataclass Mapping (Type-Safe & Object-Oriented)
A robust choice as you grow your Python skills—adds type hints and encapsulation for clarity:
from dataclasses import dataclass # Define a dataclass to hold our parameters with clear type hints @dataclass class OrbitingBody: primary_radius: float gravitational_param: float # Map body names to their dataclass instances body_params = { "Ariel": OrbitingBody(578.9, 90.099), "Callisto": OrbitingBody(2410.3, 7181.224), "Ceres": OrbitingBody(481.5, 62.66886) } orbiting_body = input("Enter the orbiting body: ").strip() params = body_params.get(orbiting_body) if params: primary_body_radius = params.primary_radius gravitational_parameter = params.gravitational_param else: print(f"Oops! '{orbiting_body}' isn't a recognized orbiting body.") primary_body_radius = None gravitational_parameter = None
Extra Tips for Polish
- Handle Case Insensitivity: If users might input "ariel" instead of "Ariel", normalize the input and dictionary keys:
orbiting_body = input("Enter the orbiting body: ").strip().capitalize() # Or make all keys lowercase and convert input to lowercase - Add Default Values: Instead of setting
None, you could define fallback parameters for unknown bodies if that makes sense for your use case.
内容的提问来源于stack exchange,提问作者SoRobby

