有什么区别?我在打印输出中看不到一个,但例如,Hackerrank在一个练习中将“l.sort(reverse=True)”提供的结果评为错误,而将“l.reverse()”评为正确
这是我的代码(我知道不是为了方便而优化的):
#HR Lists
commands = "insert", "print", "remove", "append", "sort", "pop", "reverse", "rev"
#Anzahl Kommandos
N = int(input())
liste = []
command = []
for i in range (0, N):
command.append(input().strip().split(" "))
if command[i][0] == commands[0]:
liste.insert(int(command[i][1]), int(command[i][2]))
elif command[i][0] == commands[1]:
print(liste)
elif command[i][0] == commands[2]:
liste.remove(int(command[i][1]))
elif command[i][0] == commands[3]:
liste.append(int(command[i][1]))
elif command[i][0] == commands[4]:
liste.sort()
elif command[i][0] == commands[5]:
liste.pop()
elif command[i][0] == commands[6]:
liste.reverse()
elif command[i][0] == commands[7]:
liste.sort(reverse=True)
print(liste)
print(command)
谢谢你的评论
list.sort(...)
顾名思义,它对列表进行排序。如果列表未排序,list.sort(reverse=True)
将按相反顺序对其排序。如果列表已经排序,它将按相反顺序排序(即反转),但可能需要更长的时间list.reverse()
简单地反转列表,这可能是您想要的这里有两个例子,它们具有完全相同的列表
l
,这里有两个不同的结果:结果:
['d', 'c', 'b', 'a']
sort(reverse=True)
按相反顺序对列表排序('a'
最后一个,'b'
最后一个之前,依此类推)结果:
['d', 'b', 'c', 'a']
reverse()
只是在不排序的情况下反转列表(将最后一个项目放在第一位,最后一个之前的项目变为第二个…依此类推)这是一个你想完成什么的问题。如果只是颠倒顺序-那么颠倒()。如果还需要注意值,则排序()
相关问题 更多 >
编程相关推荐