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

HackerRank Python列表练习题执行sort时抛TypeError原因咨询

HackerRank Python列表操作题报错排查

题目基础信息

  • 题目来源:HackerRank平台Prepare模块List类Python练习题

样例输入

12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print

预期输出

[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]

原代码及报错信息

原解题代码:

if __name__ == '__main__':
    l=[]
    N = int(input())
    for z in range(N):
        x=input().split()
        if (x[0]=="insert"):
            l.insert(int(x[1]),int(x[2]))
        elif(x[0]=="print"):
            print(l)
        elif(x[0]=="remove"):
            l.remove(int(x[1]))
        elif (x[0]=="append"):
            l.append(x[1])
        elif(x[0]=="sort"):
            l.sort()
        elif(x[0])=="pop":
            l.pop()
        elif(x[0]=="reverse"):
            l.reverse()

运行抛出错误:

Traceback (most recent call last):
File "/tmp/submission/20220617/03/45/hackerrank-3495035b4042c8bc0c55e799a2d2e687/code/Solution.py", line 15, in <module>
l.sort()
TypeError: '<' not supported between instances of 'str' and 'int'

错误原因

报错核心原因是列表内同时存在整数、字符串两种数据类型,调用sort()方法时无法完成跨类型比较:

  • 处理insert、remove逻辑时,传入的数值参数都通过int()做了类型转换,存入列表的是整数类型
  • 处理append逻辑时,直接将input().split()拆分得到的字符串类型值x[1]追加进列表,没有做整数转换,导致列表混入字符串元素
  • Python3不支持直接比较整数和字符串的大小,执行排序时直接触发类型错误
    额外书写问题:pop分支的判断条件括号位置错误,写为elif(x[0])=="pop":,虽然不影响当前逻辑触发,但属于不规范写法,正确写法为elif x[0] == "pop":

修正方案

只需要给append分支的追加值补上int()类型转换,同时修正pop分支的判断书写即可,修正后可运行代码如下:

if __name__ == '__main__':
    l = []
    N = int(input())
    for z in range(N):
        x = input().split()
        if x[0] == "insert":
            l.insert(int(x[1]), int(x[2]))
        elif x[0] == "print":
            print(l)
        elif x[0] == "remove":
            l.remove(int(x[1]))
        elif x[0] == "append":
            l.append(int(x[1]))
        elif x[0] == "sort":
            l.sort()
        elif x[0] == "pop":
            l.pop()
        elif x[0] == "reverse":
            l.reverse()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 07:15:39