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

如何从列表调用索引并在打印中引用?优化多分支判断逻辑

优化行星旅行选择的实现方式

首先,你当前代码里的条件判断存在逻辑错误:if response == recordedPlanets[0] or recordedPlanets[0].lower() 这种写法会导致第一个分支永远触发——因为recordedPlanets[0].lower()只要不是空字符串就会被视为True,后面的elif分支根本不会执行。正确的大小写不敏感匹配应该写成 response.lower() == recordedPlanets[0].lower()。

回到你的核心需求:完全不需要为每个列表元素单独编写elif,以下几种方法可以高效适配任意长度的recordedPlanets列表:

方法1:遍历列表查找匹配项

直接遍历列表,统一将输入和行星名转为小写实现大小写不敏感匹配,找到匹配项后打印并终止循环:

def travelToPlanet():
    print()
    print("Please enter the name of the planet you'd like to travel to.")
    print()
    print(recordedPlanets)
    response = input("> ").lower()
    for planet in recordedPlanets:
        if response == planet.lower():
            print(f"Traveling to {planet}.")
            break
    else:
        # 未找到匹配项时的提示
        print("That planet isn't in our records.")

方法2:字典快速映射(适合大列表场景)

如果recordedPlanets包含大量元素,遍历的效率不够高,可以提前构建一个“小写行星名→原行星名”的字典,查找操作的时间复杂度为O(1):

# 可在函数外部初始化,避免每次调用都重建字典
planet_lookup = {p.lower(): p for p in recordedPlanets}

def travelToPlanet():
    print()
    print("Please enter the name of the planet you'd like to travel to.")
    print()
    print(recordedPlanets)
    response = input("> ").lower()
    if response in planet_lookup:
        print(f"Traveling to {planet_lookup[response]}.")
    else:
        print("That planet isn't in our records.")

方法3:简洁的生成器匹配

用next()函数配合生成器表达式,一行代码快速定位匹配项,代码更紧凑:

def travelToPlanet():
    print()
    print("Please enter the name of the planet you'd like to travel to.")
    print()
    print(recordedPlanets)
    response = input("> ").lower()
    matched_planet = next((p for p in recordedPlanets if p.lower() == response), None)
    if matched_planet:
        print(f"Traveling to {matched_planet}.")

以上三种方法都能自动适配recordedPlanets的长度,新增行星时完全不需要修改函数逻辑。

内容的提问来源于stack exchange,提问作者Kukul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:08:12