Python中实现用户按运动及年龄组选择调用对应函数的最优方案
Hey there! Great question—this is exactly the kind of scenario where dictionary mapping shines in Python. It’s way cleaner, more scalable, and easier to maintain than a tangled mess of if/elif statements. Here’s how to pull this off smoothly:
Step 1: Set up your function mappings
First, you’ll want to create a dictionary that links user input combinations (sport + age group) directly to their corresponding functions. This acts like a lookup table for your code.
Option A: Manual import (simple for small sets)
If you don’t mind writing out the imports for your 20 functions, start by importing each one into your main file:
# Import all your sport/age group functions from footballAdults import footballAdults from footballTeens import footballTeens from footballKids import footballKids from tennisAdults import tennisAdults # ... repeat for all 20 functions
Then build your mapping dictionary. We’ll use lowercase tuples as keys to handle case-insensitive user input:
# Create a lookup dictionary: (sport, age_group) -> function sport_age_lookup = { ("football", "adults"): footballAdults, ("football", "teens"): footballTeens, ("football", "kids"): footballKids, ("tennis", "adults"): tennisAdults, # ... add all remaining sport/age combinations here }
Option B: Dynamic import (scalable for large sets)
Since you have 20 separate files (each with one function), manually importing every single one can get tedious. Instead, use Python’s importlib to dynamically load modules based on naming patterns (assuming your function names match their file names, e.g., footballAdults.py contains footballAdults()):
import importlib # Define all valid sport/age pairs first valid_pairs = [ ("football", "adults"), ("football", "teens"), ("football", "kids"), ("tennis", "adults"), # ... list all 20 valid combinations here ] # Build the lookup dictionary dynamically sport_age_lookup = {} for sport, age in valid_pairs: # Construct the function/module name (e.g., "football" + "Adults" = "footballAdults") func_name = f"{sport}{age.capitalize()}" # Dynamically import the module module = importlib.import_module(func_name) # Grab the function from the module and add to the lookup sport_age_lookup[(sport.lower(), age.lower())] = getattr(module, func_name)
Step 2: Handle user input & call the function
Now write the user interaction logic. We’ll standardize input (lowercase, trim whitespace) to avoid mismatches from capitalization or typos:
# Get and clean user input selected_sport = input("Pick a sport: ").strip().lower() selected_age = input("Pick an age group: ").strip().lower() # Look up the corresponding function target_function = sport_age_lookup.get((selected_sport, selected_age)) # Execute the function if it exists, else show an error if target_function: target_function() else: print("Oops! That sport and age group combination isn't available.")
Why this is the best approach
- Scalability: Adding a new sport/age group only requires adding a new entry to the
valid_pairslist (or the lookup dictionary) and creating the corresponding function file—no need to rewrite core logic. - Readability: The lookup dictionary makes it instantly clear which input maps to which function, unlike a long chain of
if/elifchecks. - Maintainability: If you ever need to rename a function or adjust its mapping, you only change one line in the dictionary instead of hunting through conditional statements.
内容的提问来源于stack exchange,提问作者Versace

