You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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_pairs list (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/elif checks.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:09:21