简体   繁体   English

Python:根据一个列表的索引对字典列表进行排序

[英]Python: sorting the lists of dictionary based on the indices of one list

So I have dict like the following: 所以我有这样的dict:

dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]}

How can I sort the lists in dict1 based on the indices that would sort one of the lists. 如何根据将对列表之一进行排序的索引对dict1的列表进行排序。 Such as the sorted indices of list 如列表的排序索引

[11, 10, 9, 8, 7]

which is 这是

[4, 3, 2, 1, 0]

So the new dict1 will be: 因此,新的dict1将是:

dict1 = {1: [3, 4, 2, 1, -1], 2: [7, 8, 9, 10, 11]}

I have tried the code like this: 我已经尝试过这样的代码:

sorted(dict1.items(), key=lambda t: t[1])

But still cannot figure it out? 但是仍然无法弄清楚吗? I can use a for loop to do this work but I believe there exist a more pythonic way. 我可以使用for循环来完成这项工作,但我相信存在一种更Python化的方式。 Any idea? 任何想法?

One way would be to compute the index list and apply it to all lists: 一种方法是计算索引列表并将其应用于所有列表:

>>> dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]}
>>> basis = dict1[2]
>>> indexes = sorted(range(len(basis)), key=basis.__getitem__)
>>> for lst in dict1.values():
        lst[:] = [lst[i] for i in indexes]

>>> dict1
{1: [3, 4, 2, 1, -1], 2: [7, 8, 9, 10, 11]}

If you're ok with "the first" list determining the order (you only said "based on [...] one of the lists" ), you could also build columns and sort those: 如果可以确定第一个列表的顺序(您只说“基于列表中的一个” ),则还可以构建列并对它们进行排序:

>>> dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]}
>>> dict(zip(dict1.keys(), zip(*sorted(zip(*dict1.values())))))
{1: (-1, 1, 2, 3, 4), 2: (11, 10, 9, 7, 8)}

Sort using enumerate to get the sorted indexes and just use the indexes to sort the other lists: 使用枚举进行排序以获取排序的索引,而仅使用索引对其他列表进行排序:

from operator import itemgetter
dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]}

l = [i for i, _ in sorted(enumerate(dict1[2]), key=itemgetter(1))]


for v in dict1.values():
    v[:] = (v[i] for i in l)
print(dict1)

Or if you want a new dict: 或者,如果您想要一个新的字典:

l = [i for i, _ in sorted(enumerate(dict1[2]), key=itemgetter(1))]
new = {k: [v[i] for i in l] for k, v in dict1.items()}

Or if you don't mind tuples: 或者,如果您不介意元组:

new = {k: itemgetter(*l)(v) for k, v in dict1.items()})

Using itemgetter in a dictionary comprehension 字典理解中使用itemgetter

>>> from operator import itemgetter
>>> order = [4, 3, 2, 1, 0]
>>> key = itemgetter(*order)
>>> {k: key(dict1[k]) for k in dict1}
{1: (3, 4, 2, 1, -1), 2: (7, 8, 9, 10, 11)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM