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

《Automate the Boring Stuff》逗号代码练习:双元素列表逗号修正

逗号代码练习修正方案

原代码的问题在于未区分双元素列表与多元素列表的格式差异:当列表只有两个元素时,会错误输出带多余逗号的格式(如apples, and bana),而正确语法应该是apples and bana。

以下是修正后的代码,通过明确的分支判断处理不同长度的列表:

def commacode(passedlist):
    # 处理空列表情况(可选,根据需求调整)
    if len(passedlist) == 0:
        return ""
    # 单元素列表直接返回元素本身
    elif len(passedlist) == 1:
        return str(passedlist[0])
    # 双元素列表直接用"and"连接,无逗号
    elif len(passedlist) == 2:
        return f"{str(passedlist[0])} and {str(passedlist[1])}"
    # 多元素列表:前面元素用逗号分隔,最后一个元素前加", and"
    else:
        stringy = ""
        for i in range(len(passedlist)-1):
            stringy += str(passedlist[i]) + ", "
        stringy += "and " + str(passedlist[-1])
        return stringy

# 测试不同场景
print(commacode(['apples', 'bana']))          # 输出: apples and bana
print(commacode(['apples','bana', 'apple'])) # 输出: apples, bana, and apple
print(commacode(['orange']))                 # 输出: orange

修正说明

  • 新增空列表分支(可选):避免空列表传入时出现索引错误
  • 双元素分支:直接拼接两个元素和"and",跳过循环添加逗号的步骤,确保格式符合语法规范
  • 多元素分支保留原逻辑,保证前面元素用逗号分隔,最后一个元素前添加", and"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:52:09