简体   繁体   English

Python将排序的字典转换为列表?

[英]Python Converting a sorted dictionary to list?

I have two lists 我有两个清单

L1 = ['tom', 'jerry', 'spike', 'fido', 'donald', 'mickey']
L2 = [3,5,7,6,9,3]
dictionary = dict(zip(L1, L2))
print dictionary

sorted_friends = sorted(dictionary.iteritems(), key = operator.itemgetter(1), reverse= True)
print sorted_friends

Basically, I am creating a dictionary from L1 and L2. 基本上,我正在根据L1和L2创建字典。 {'mickey': 3, 'tom': 3, 'jerry': 5, 'donald': 9, 'fido': 6, 'spike': 7} Sorting (reverse) sorting it by value, which gives me: [('donald', 9), ('spike', 7), ('fido', 6), ('jerry', 5), ('mickey', 3), ('tom', 3)] {'mickey': 3, 'tom': 3, 'jerry': 5, 'donald': 9, 'fido': 6, 'spike': 7}对值进行排序(反向)排序,这使我: [('donald', 9), ('spike', 7), ('fido', 6), ('jerry', 5), ('mickey', 3), ('tom', 3)]

I want a list of the top 3 keys: like [donald,spike,fido] But the problem is if I use any method that I know like casting to dict() etc its spoiling the sorting. 我想要列出前3个键:例如[donald,spike,fido]但是问题是,如果我使用任何我知道的方法,例如将其强制转换为dict()等,会破坏排序。

No need to use a dict; 无需使用字典; just create the list of tuples and sort them by the appropriate field. 只需创建元组列表并按适当的字段对其进行排序即可。

sorted(zip(L1, L2), key=lambda x: x[1], reverse=True)[:3]

You can of course use operator.itemgetter(1) instead of the lambda, as you please. 当然,您可以根据需要使用operator.itemgetter(1)代替lambda。

If you just want the names after the fact, you can modify this: 如果您只想在事实之后加上名称,则可以进行以下修改:

[a for a,_ in sorted(zip(L1, L2), key=lambda x: x[1], reverse=True)][:3]

Note that you could also conveniently avoid having to specify a custom sort function at all by simply reversing the order: 请注意,您还可以通过简单地颠倒顺序来方便地避免完全指定自定义排序功能:

[b for _,b in sorted(zip(L2, L1), reverse=True)][:3]

This works because the default sort order for tuples sorts them according to their first element, then their second, and so on - so it will sort by the values first. 之所以可行,是因为元组的默认排序顺序是根据元组的第一个元素,然后是第二个元素对它们进行排序,依此类推-因此它将首先按值排序。

If you just want the 3 largest, why not just use heapq ? 如果只想要3个最大的,为什么不只使用heapq

>>> L1 = ['tom', 'jerry', 'spike', 'fido', 'donald', 'mickey']
>>> L2 = [3,5,7,6,9,3]
>>> dictionary = dict(zip(L1, L2))
>>> import heapq
>>> heapq.nlargest(3, dictionary, key=dictionary.get)
['donald', 'spike', 'fido']

It's also possible, but a little tricky to skip creating the dictionary 也可以,但是要跳过创建词典的操作有些棘手

>>> heapq.nlargest(3, L1, key=lambda x, i2=iter(L2): next(i2))
['donald', 'spike', 'fido']

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

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