python - 如何对值进行排序并按降序将其放入数组中?
问题描述
如何对值进行排序并直接在 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}]
解决方案
您可以使用堆队列:
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)
这种情况下的基数排序。
推荐阅读
- scala - SparkStream 无法从 Kafka 主题中读取数据
- javascript - JS:传递一个包含函数/方法属性的对象,然后在另一个文件中传递和调用传入的对象函数/方法属性?
- redhat - 错误:解析数据库架构失败:在 dpdk 端口上运行 ovs-tcpdump 时,成员“名称”的类型不匹配
- unity3d - 切换以激活/停用游戏对象
- vue.js - snabdom、hyperscript 和 Vue 2 有什么关系?
- java - 我的“/” requestMapping 向我发送了 WhiteLabel“/”错误
- javascript - 在选择时显示选定的下拉项
- pandas - Spark 与 Scala 和 Pandas
- python - 我在这里想念什么?python中的简单for循环
- html - 如何从列表中创建新的 HtmlAgilityPack.HtmlDocument
从第一次“选择/过滤”运行?