首页 > 解决方案 > 如何对值进行排序并按降序将其放入数组中?

问题描述

如何对值进行排序并直接在 for 循环本身中按降序将其放置在数组中,而不是在 for 循环之后使用 sorted 函数?

final_lst = []
for row in data:
    score = function_returns_a_score()
    final_lst.append({"score": score})

print(final_lst)
# returns 
# [{"score": 10}, {"score": 40}, {"score": 90}, {"score": 15}]

print(sorted(final_lst, key=lambda k: k['score'], reverse=True))
# returns
# [{'score': 90}, {'score': 40}, {'score': 15}, {'score': 10}]

标签: pythonpython-3.x

解决方案


您可以使用堆队列

import random
import heapq

final_list = []
for score in random.sample(range(100), 20): # in random order
    # negative because we're sorting in reverse order
    heapq.heappush(final_list, -score)

final_list = [{'score': -heapq.heappop(final_list)} for _ in range(len(final_list))]

样本结果:

[{'score': 95}, {'score': 94}, {'score': 89}, {'score': 72}, {'score': 71}, {'score': 65}, {'score': 60}, {'score': 58}, {'score': 51}, {'score': 50}, {'score': 45}, {'score': 44}, {'score': 36}, {'score': 35}, {'score': 33}, {'score': 26}, {'score': 25}, {'score': 18}, {'score': 6}, {'score': 3}]

我不确定这是否比排序具有更好的复杂性,但它可以让您随时按排序顺序提取数据:您可以heapq.heappop(final_list) 在需要下一个值时调用- 相反,排序是在此时此地完成的。


此外,如果您的分数是固定宽度的整数(例如,从 0 到 100 的整数),您可以使用O(3n)这种情况下的基数排序。


推荐阅读