首页 > 解决方案 > 排序列表的字典排序使得值列表的第 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]}

我担心可能存在本身没有最佳解决方案的情况,在这种情况下,我对任意选择解决方案感到满意。

标签: pythonpython-3.xlistsortingdictionary

解决方案


  1. 对于每个列表,找到最大元素的索引
  2. 按该索引对列表进行分组
  3. 从每个组中选择一个任意元素并将其放入正确索引处的结果中
  4. 使用剩余元素填充结果中的空槽
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])])

我使用的有用的函数和类:


推荐阅读