示例输入:
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()
错误信息-回溯(最近一次调用):文件"/tmp/submission/20220617/03/45/hackerrank-3495035b4042c8bc0c55e799a2d2e687/code/Solution.py"l.sort ()TypeError: '<'在'str'和'int'实例之间不支持
您在x[0] == "append"
上附加了字符串值。
当您更改为l.append(int(x[1])
时,它应该可以工作
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()