Dee*_*k B 1 python dictionary list
我有两个清单
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
Run Code Online (Sandbox Code Playgroud)
基本上,我正在创建一个L1和L2的字典.
{'mickey': 3, 'tom': 3, 'jerry': 5, 'donald': 9, 'fido': 6, 'spike': 7}
按值排序(反向)排序,这给了我:[('donald', 9), ('spike', 7), ('fido', 6), ('jerry', 5), ('mickey', 3), ('tom', 3)]
我想要一个前3个键的列表:喜欢[donald,spike,fido]
但问题是如果我使用任何我知道的方法,如dict()等,它会破坏排序.
不需要使用词典; 只需创建元组列表并按适当的字段对它们进行排序.
sorted(zip(L1, L2), key=lambda x: x[1], reverse=True)[:3]
Run Code Online (Sandbox Code Playgroud)
你可以随意使用operator.itemgetter(1)而不是lambda.
如果你只是想要事后的名字,你可以修改这个:
[a for a,_ in sorted(zip(L1, L2), key=lambda x: x[1], reverse=True)][:3]
Run Code Online (Sandbox Code Playgroud)
请注意,您也可以通过简单地颠倒顺序来方便地避免必须指定自定义排序功能:
[b for _,b in sorted(zip(L2, L1), reverse=True)][:3]
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为元组的默认排序顺序是根据它们的第一个元素,然后是第二个元素对它们进行排序,依此类推 - 所以它将首先按值排序.