Python 列表的排序字典,其排序方式为值列表的第i个索引最大的项
在python 3中工作时,我遇到以下问题: 我的字典由单位(键)和活动列表(值)组成,我必须对它进行排序,以便按峰值活动进行排序。这意味着我想找到每个索引I,该dict项的第I个值是值列表中的最高值Python 列表的排序字典,其排序方式为值列表的第i个索引最大的项,python,python-3.x,list,sorting,dictionary,Python,Python 3.x,List,Sorting,Dictionary,在python 3中工作时,我遇到以下问题: 我的字典由单位(键)和活动列表(值)组成,我必须对它进行排序,以便按峰值活动进行排序。这意味着我想找到每个索引I,该dict项的第I个值是值列表中的最高值 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]} 我担心这可
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]}
我担心这可能是一种情况,即本身没有一个最佳的解决方案,在这种情况下,我很高兴有一个任意选择的解决方案
- 分组
- 存储结果
- 作为
- 并从dict中获取任意元素
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])])