作为一个人为的例子,我有一本字典,它是这样设置的:
{
'a': ['a', 'b'],
'b': ['a', 'b', 'c'],
'c': ['a', 'b', 'c', 'd']
}
我想按列表的长度(即每个条目的值)按降序对字典进行排序,因此结果应该是:
^{pr2}$我试过这样做:
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()
函数按我想要的方式排序,我需要做些什么?在
您可以使用
lambda
。比如:或者,你可以不使用听写理解,就像阿兰·菲所说:
^{pr2}$将
sorted
与key
一起使用。在例如:
输出:
^{pr2}$如果想维持秩序。
使用^{}
{{1}如果你想使用^ 1}的话。您可以使用
key
对第一个dict
中的项目进行排序。在代码
输出
^{pr2}$python3.6+
dict
是有序的尽管,如果使用python3.6+,插入顺序将保留为
dict
。这是特定于CPython实现的,它将仅是一个official language feature starting at version 3.7。在代码
输出
相关问题 更多 >
编程相关推荐