[英]How do I create a comprehension that sorts by the number of values in a dictionary?
Currently, I am trying to learn more about how to utilize comprehensions.目前,我正在尝试更多地了解如何使用理解。 However, I am stuck with this problem I have right now.但是,我现在遇到了这个问题。
The dictionary I have:我有的字典:
d = {'Second': {('Carrie', 3), ('Diane', 3), ('Bob', 3)},
'Third': {('Alan', 2), ('Diane', 5)},
'Fourth': {('Carrie', 2), ('Alan', 5)},
'First': {('Bob', 5), ('Carrie', 5), ('Alan', 1), ('Diane', 1)} }
I am trying to sort it by the number of values each key has so it would look like this when returned.我正在尝试按每个键具有的值数对其进行排序,以便返回时看起来像这样。 If the key both have the same amount of values, it would be sorted alphabetically.如果键都具有相同数量的值,则将按字母顺序排序。
Desired Output:期望输出:
['First', 'Second', 'Fourth', 'Third']
What I have so far however, I am unsure how to sort by the len of the values :但是,到目前为止,我不确定如何按值的 len 进行排序:
d = {'Second': {('Carrie', 3), ('Diane', 3), ('Bob', 3)}, 'Third': {('Alan', 2), ('Diane', 5)}, 'Fourth': {('Carrie', 2), ('Alan', 5)}, 'First': {('Bob', 5), ('Carrie', 5), ('Alan', 1), ('Diane', 1)} }
def sorting(d):
return sorted([key for key, value in db.items(), key = lambda x: -len( )
Create a dictionary mapping keys to their length, and then call sorted
on that.创建一个字典,将键映射到它们的长度,然后调用sorted
。
d2 = {k: len(d[k]) for k in d}
sorted(d2, key=d2.get, reverse=True)
# ['First', 'Second', 'Third', 'Fourth']
Using a lambda
would eliminate the need for a mapping, but would also mean the key is a lambda
function, ... but here it is:使用lambda
将消除对映射的需要,但也意味着键是一个lambda
函数,...但这里是:
sorted(d, key=lambda k: (len(d[k]), k), reverse=True)
# ['First', 'Second', 'Third', 'Fourth']
Here, the key callback returns a tuple (len(d[k]), k)
ensuring that sorting is first done by the length, and then in alphabetical order.在这里,键回调返回一个元组(len(d[k]), k)
确保排序首先按长度完成,然后按字母顺序完成。
As a silly one-liner, you can do this:作为一个愚蠢的单线,你可以这样做:
(lambda d: sorted(d, key=d.get, reverse=True))({k: len(d[k]) for k in d})
# ['First', 'Second', 'Third', 'Fourth']
This is just a stand-in for assignment expressions, I'm waiting for python-3.8.这只是赋值表达式的替代品,我在等 python-3.8。
You can use the reverse
parameter in the sorted
function:您可以在sorted
函数中使用reverse
参数:
results = [a for a, _ in sorted(d.items(), key=lambda x:len(x[-1]), reverse=True)]
Output:输出:
['First', 'Second', 'Third', 'Fourth']
Just have a lambda
that returns two values.只需有一个返回两个值的lambda
。 The length of the value, and a list of negative ord
's of all the characters in the key to negate the reverse = True
for alphabetical sorting.值的长度,以及键中所有字符的负数ord
的列表,以否定reverse = True
以进行字母排序。
print(sorted(d.keys(), key = lambda a: (len(d[a]), [-ord(c.lower()) for c in a]), reverse = True))
#['First', 'Second', 'Fourth', 'Third']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.