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

Python自定义palindromes函数判断回文列表运行报错如何解决

问题排查及修正

存在的问题

  • 遍历取值逻辑错误:for word in input_list 循环里的word已经是从列表中取出的字符串元素,不能再用input_list[word](列表索引必须为整数,传入字符串会直接触发TypeError报错)
  • 反转字符串对比逻辑错误:Python内置的reversed()返回的是反转迭代器对象,不是反转后的字符串,直接和原字符串对比永远返回False,正确的字符串反转可以用切片语法[::-1]
  • 函数无返回值:当前函数仅打印单条判断结果,没有收集结果并返回,调用后拿到的output会是None,无法得到预期的布尔值列表

修正后的代码

input_list = ['tacocat', 'bob', 'davey']

def palindromes(input_list):
    res = []
    for word in input_list:
        # 直接用取出的字符串元素,切片反转后对比
        res.append(word == word[::-1])
    return res

output = palindromes(input_list)
print(output)

运行后输出结果为:[True, True, False],符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:36:03