作者cccx (ccc)
看板Python
标题Re: [问题] 想请教一个问题
时间Thu Feb 10 23:13:07 2011
试着解决大量数值做sort会很慢的问题
想法: 不要全部一起sort
每次只挑一个数字出来,跟当下最大的五个数字比
所以每次最多有6个数字做sort
L = ['369','638','724','920','14','50','11','65', '920', '920']
max5 = [] # 目前最大的5个数字及位置
threshold = 0 # max5里面最小的数值,作为筛选用
for i, str_num in enumerate(L):
num = int(str_num)
if num <= threshold: # 比前五名还小就直接跳过
continue
# 够格的数字就可以挑战前5大
max5.append((num, i))
max5.sort(reverse=True)
while len(max5) > 5: # 踢掉比输的
max5.pop()
threshold = max5[-1][0] # 拿前五大里面,最小的当筛选标准
print [x[1] for x in max5] # 印结果
※ 引述《perturb (背後有老板)》之铭言:
: 参考apua的做法稍加改变满足DP1010以输出重复最大值的位置
: >>> L = ['369','638','724','920','14','50','11','65', '920', '920']
: >>> Li = zip(L, range(len(L)))
: >>> Li.sort(key=lambda x:int(x[0]), reverse=True)
: >>> print [x[1] for x in Li[:5]]
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 123.195.30.39
1F:→ uranusjr:这个作法比较好, 没有要全比的状态下用 sort 太浪费 02/11 02:11
2F:→ juiz:怎麽大家都不爱用 numpy.argsort() 02/11 02:56
3F:→ apua:@o@!研究一下numpy.argsort~ 02/11 15:30