python - 排序列表的字典排序使得值列表的第 i 个索引最大的项目
问题描述
在python 3中工作我遇到了以下问题:
我的字典由单位(键)和活动列表(值)组成,我必须对其进行排序,以便按峰值活动排名。这意味着我想找到每个索引 i,这个第 i 个值是值列表中的最大值的 dict 项。
example_dict = {unit1: [1, 4, 3], unit2: [2, 2, 2], unit3: [1, 1, 1]}
sorted_dict = {unit2: [2, 2, 2], unit1: [1, 4, 3], unit3: [1, 1, 1]}
我担心可能存在本身没有最佳解决方案的情况,在这种情况下,我对任意选择解决方案感到满意。
解决方案
- 对于每个列表,找到最大元素的索引
- 按该索引对列表进行分组
- 从每个组中选择一个任意元素并将其放入正确索引处的结果中
- 使用剩余元素填充结果中的空槽
import operator
import collections
example_dict = {'unit1': [1, 4, 3],
'unit2': [2, 2, 2],
'unit3': [1, 1, 1]}
# group the lists by the index of their maximum element
lists_by_max_index = collections.defaultdict(list)
for key, values in example_dict.items():
# find the index of the maximum element
max_index, max_value = max(enumerate(values), key=operator.itemgetter(1))
# and store the key in the corresponding group
lists_by_max_index[max_index].append(key)
# list_by_max_index is now {1: ['unit1'], 0: ['unit2', 'unit3']}
# make a list representing the sorted dict and initialize it to None
sorted_keys = [None] * len(next(iter(example_dict.values())))
unused_keys = []
# sorted_keys is [None, None, None]
# for each group in the dict we created earlier, put a random key into
# the list
for i, keys in lists_by_max_index.items():
sorted_keys[i] = keys.pop()
unused_keys += keys # store the other keys for later
# sorted_keys is now ['unit3', 'unit1', None]
# iterate over the list and fill any empty slots with arbitrary unused keys
for i, key in enumerate(sorted_keys):
if key is None:
sorted_keys[i] = unused_keys.pop()
# sorted_keys is now ['unit3', 'unit1', 'unit2']
# finally, grab the corresponding value for each key and turn the whole thing
# into an OrderedDict
sorted_dict = [(key, example_dict[key]) for key in sorted_keys]
sorted_dict = collections.OrderedDict(sorted_dict)
print(sorted_dict)
# output:
# OrderedDict([('unit3', [1, 1, 1]),
# ('unit1', [1, 4, 3]),
# ('unit2', [2, 2, 2])])
我使用的有用的函数和类:
collections.defaultdict
用于分组collections.OrderedDict
存储结果operator.itemgetter
作为一个关键功能sorted
iter
并next
从字典中获取任意元素
推荐阅读
- php - Flutter Firebase Auth - PHP 服务器中的令牌验证问题
- excel - 基于“是否为空”合并行值
- reactjs - 无法通过 API 调用访问对象数据
- ios - SwiftUI:如何让 NavigationLink 不去任何地方并停留在当前视图上
- r - 为什么 ggplot2 会给出一个空的情节?
- javascript - 如何简化不同seclcet上的重复条件语句?
- c++ - 如何检查分配给呼叫操作员结果的类型?
- sql - 需要一个存储过程/查询,它将从现有表中返回 MS SQL 的结果
- windows - 从 nsh 文件 nsis 中检索变量值
- flutter - 屏幕无法实时更新,直到滚动到底部