对列表进行排序的字典,使得值列表的第i个索引为大的项

2024-03-29 01:59:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python3中,我遇到了以下问题:

我的字典由单位(键)和活动列表(值)组成,我必须按活动峰值排序。这意味着我想找到每个索引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]}

我担心这可能是一种情况,即本身没有一个最佳的解决方案,在这种情况下,我很高兴与任意选择的解决方案。你知道吗


Tags: 列表字典排序example情况单位解决方案dict
1条回答
网友
1楼 · 发布于 2024-03-29 01:59:22
  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])])

我使用的有用函数和类:

  • ^{}用于分组
  • ^{}来存储结果
  • ^{}作为^{}的键函数
  • ^{}^{}从dict获取任意元素

相关问题 更多 >