私信  •  关注

mayurmadnani

mayurmadnani 最近创建的主题
mayurmadnani 最近回复了
6 年前
回复了 mayurmadnani 创建的主题 » python高效的字典中的并行列表排序

首先,使用指定的键进行排序,您可以获得索引顺序。你按顺序重新排列字典中剩下的列表。

unsorted_my_dict = {
'key_one': [1, 6, 2, 3],
'key_two': [4, 1, 9, 7],
'key_three': [1, 2, 4, 3],
}


def sort_parallel_by_key(my_dict, key):
    def sort_by_indices(idx_seq):
        return {k: [v[i] for i in idx_seq] for k, v in my_dict.items()}

    indexes = [idx for idx, _ in sorted(enumerate(my_dict[key]), key=lambda foo: foo[1])]
    return sort_by_indices(indexes)


print(sort_parallel_by_key(unsorted_my_dict, 'key_three'))