LBa*_*ish 2 python python-3.x python-3.4
标题几乎说明了一切,我正在寻找有效排序并行列表的字典.
unsorted_my_dict = {
'key_one': [1,6,2,3],
'key_two': [4,1,9,7],
'key_three': [1,2,4,3],
...
}
sorted_my_dict = {
'key_one': [1,6,3,2],
'key_two': [4,1,7,9],
'key_three': [1,2,3,4],
...
}
Run Code Online (Sandbox Code Playgroud)
我想排序key_three,并且该字典中的所有其他列表并行.有一些类似的问题,但我正在努力,因为我在字典中有一个未知数量的键要排序,我只知道我想要排序的键的名称(key_three).
希望用vanilla Python做到这一点,没有第三方依赖.
编辑1:我是什么意思并行?我的意思是,如果我排序key_three,这需要交换最后两个值,字典中的所有其他列表也将交换它们的最后两个值.
编辑2:Python 3.4具体
您可以先对enumerate目标列表进行排序,以恢复所需的索引顺序,然后按顺序重新排列每个列表.
my_dict = {
'key_one': [1,6,2,3],
'key_two': [4,1,9,7],
'key_three': [1,2,4,3],
}
def parallel_sort(d, key):
index_order = [i for i, _ in sorted(enumerate(d[key]), key=lambda x: x[1])]
return {k: [v[i] for i in index_order] for k, v in d.items()}
print(parallel_sort(my_dict, 'key_three'))
Run Code Online (Sandbox Code Playgroud)
{'key_one': [1, 6, 3, 2],
'key_two': [4, 1, 7, 9],
'key_three': [1, 2, 3, 4]}
Run Code Online (Sandbox Code Playgroud)