【问题标题】:Sorting a list of dictionary based on the length of one of the values of the dictionary根据字典值之一的长度对字典列表进行排序
【发布时间】:2019-01-17 16:45:17
【问题描述】:

我有一个字典列表。字典有一个名为 friends 的键,其值是一个 id 列表。我想根据好友列表中的 id 数量对字典列表进行排序。

users=[{'id': 0, 'name': 'Hero', 'friends': [1, 2]}, 
{'id': 1, 'name': 'Dunn', 'friends': [0, 2, 3]},
{'id': 2, 'name': 'Sue', 'friends': [0, 1, 3]},
{'id': 3, 'name': 'Chi', 'friends': [1, 2, 4]}, 
{'id': 4, 'name': 'Thor', 'friends': [3, 5]}, 
{'id': 5, 'name': 'Clive', 'friends': [4, 6, 7]},
{'id': 6, 'name': 'Hicks', 'friends': [5, 8]}, 
{'id': 7, 'name': 'Devin', 'friends': [5, 8]}, 
{'id': 8, 'name': 'Kate', 'friends': [6, 7, 9]},
{'id': 9, 'name': 'Klein', 'friends': [8]}]

我该如何处理?

【问题讨论】:

标签: python list sorting dictionary


【解决方案1】:

我相信这就是你的意思:

sorted(users, key=lambda d: len(d['friends']))

用户列表根据好友数量进行排序。朋友较少的用户首先出现。如果两个用户有相同数量的朋友,他们出现的顺序是随机的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-23
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    相关资源
    最近更新 更多