【问题标题】:Hacker rank List Prepare黑客排名列表准备
【发布时间】:2023-02-11 14:33:32
【问题描述】:

这是我的代码,它给了我这个错误信息。为什么?

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()

错误消息 - 回溯(最后一次调用): 文件“/tmp/submission/20220617/03/45/hackerrank-3495035b4042c8bc0c55e799a2d2e687/code/Solution.py”,第 15 行,在 l.排序() TypeError: '<' 在 'str' 和 'int' 的实例之间不支持

【问题讨论】:

  • 请提供示例输入和预期输出。
  • 示例输入和输出作为答案发布
  • 这是我第一次提问,抱歉

标签: python python-3.x list sorting nested


【解决方案1】:

您在 x[0] == "append" 处附加了字符串值。

当您更改为l.append(int(x[1])时它应该可以工作

【讨论】:

    【解决方案2】:
    if __name__ == '__main__':
        N = int(input())
        myList = []
        
        for i in range(N):
            command = input().split()
            if command[0] == 'insert':
                myList.insert(int(command[1]), int(command[2]))
            elif command[0] == 'print':
                print(myList)
            elif command[0] == 'remove':
                myList.remove(int(command[1]))
            elif command[0] == 'append':
                myList.append(int(command[1]))
            elif command[0] == 'sort':
                myList.sort()
            elif command[0] == 'pop':
                myList.pop()
            elif command[0] == 'reverse':
                myList.reverse()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多