这道题最恶心的地方是相同成绩要按输入顺序输出,所以想到了用bisect模块。
bisect_left(a,num)返回num在有序序列a中的位置,如果num已经存在在a中,那就返回序列中num的位置
bisect_right(a,num)是如果num已经在a中,返回序列中最右边的num的右边位置
import bisect
while 1:
try:
n = int(input())
sort = int(input())
namelist = []
score = []
score2 = []
name2 = []
for i in range(n):
name = input().split()
namelist.append(name[0])
score.append(int(name[1]))
if sort:
for i in range(n):
place = bisect.bisect_right(score2, score[i])
name2.insert(place,namelist[i])
bisect.insort_right(score2, score[i])
for i in range(n):
print("%s %d"%(name2[i],score2[i]))
else:
for i in range(n):
place = bisect.bisect_left(score2, score[i])
name2.insert(place,namelist[i])
bisect.insort_left(score2, score[i])
for i in range(n-1,-1,-1):
print("%s %d"%(name2[i],score2[i]))
except:
break