作为一个人为的例子,我有一个设置如下的字典:
{
'a': ['a', 'b'],
'b': ['a', 'b', 'c'],
'c': ['a', 'b', 'c', 'd']
}
Run Code Online (Sandbox Code Playgroud)
我想按列表的长度(每个条目的值)按降序对字典进行排序,所以结果应该是这样的:
{
'c': ['a', 'b', 'c', 'd'],
'b': ['a', 'b', 'c'],
'a': ['a', 'b']
}
Run Code Online (Sandbox Code Playgroud)
我试图做这样的事情:
sorted_functions = sorted(
functions.items(), # Sort the actual items of the dictionary
key=len( # Sort on the length of
operator.itemgetter( # the value of the entry, which is
slice(0, None) # a list slice of the whole list
)
),
reverse=True # Sort the values in descending order
)
Run Code Online (Sandbox Code Playgroud)
但是,我收到此错误:
TypeError: object of type 'operator.itemgetter' has no len()
Run Code Online (Sandbox Code Playgroud)
在 REPL 中,我尝试了以下操作:
>>> d = { 'a': ['a'], 'b': ['a', 'b'] }
>>> itemgetter(slice(0, None))(d['a'])
['a']
>>> len(itemgetter(slice(0, None))(d['a']))
1
>>> itemgetter(slice(0, None))(d['b'])
['a', 'b']
>>> len(itemgetter(slice(0, None))(d['b']))
2
Run Code Online (Sandbox Code Playgroud)
...所以我能够获得列表的长度,但在sorted()函数中,它不起作用。
我需要做些什么不同的事情才能让sorted()函数按照我想要的方式排序?
sorted与 一起使用key。
前任:
d = {
'a': ['a', 'b'],
'b': ['a', 'b', 'c'],
'c': ['a', 'b', 'c', 'd']
}
print( sorted(d.items(), key= lambda x: len(x[1]), reverse=True) )
Run Code Online (Sandbox Code Playgroud)
输出:
[('c', ['a', 'b', 'c', 'd']), ('b', ['a', 'b', 'c']), ('a', ['a', 'b'])]
Run Code Online (Sandbox Code Playgroud)
如果要维持秩序。
import collections
d = collections.OrderedDict(sorted(d.items(), key= lambda x: len(x[1]), reverse=True))
print( d )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1936 次 |
| 最近记录: |