5w0*_*1sh 1 python sorting algorithm
我在Python中有一个小脚本,其字典与如下相同:
d = {'category_1' : ['a', 'b'],
'category_2' : ['c', 'd', 'e'],
'category_3' : ['z']}
Run Code Online (Sandbox Code Playgroud)
如何根据列表中的值数对其进行排序?我希望它看起来像:
d = {'category_3' : ['z'],
'category_1' : ['a', 'b'],
'category_2' : ['c', 'd', 'e']}
Run Code Online (Sandbox Code Playgroud)
Python中的字典是无序的.
为了实际存储排序,您需要有一个元组列表,或使用collections.OrderedDict().
>>> from collections import OrderedDict
>>> OrderedDict(sorted(d.items(), key=lambda item: len(item[1])))
OrderedDict([('category_3', ['z']), ('category_1', ['a', 'b']), ('category_2', ['c', 'd', 'e'])])
Run Code Online (Sandbox Code Playgroud)
排序是通过使用这里实现了sorted()内置的,用一个简单的key功能.
| 归档时间: |
|
| 查看次数: |
107 次 |
| 最近记录: |