作为一个人为构造的示例,我有一个类似于以下设置的字典:
{
'a': ['a', 'b'],
'b': ['a', 'b', 'c'],
'c': ['a', 'b', 'c', 'd']
}
我希望按照列表长度(即每个条目的值)的降序对字典进行排序,因此结果应该是这样的:
{
'c': ['a', 'b', 'c', 'd'],
'b': ['a', 'b', 'c'],
'a': ['a', 'b']
}
我曾试图做这样的事情:
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
)
然而,我收到了这个错误:
TypeError: object of type 'operator.itemgetter' has no len()
在 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
我可以获取列表的长度,但在sorted()
函数中,它不起作用。
我需要做什么才能让sorted()
函数按照我想要的方式排序?
dict
根据定义是无序的。您可以使用指定的键len(value)
对元素进行排序,但您必须将结果放入列表、SortedDict或其他结构中。 - Prune