【问题标题】:Slice a list of dictionaries to preserve a range of items切片字典列表以保留一系列项目
【发布时间】:2020-06-11 02:23:18
【问题描述】:

我有一个这样的字典列表,但要大得多:

newlist = sorted(l, key=lambda k: k['score'], reverse=True) 
[{'score': '4.0', 'id': 686}, {'score': '3.0', 'id': 55}, {'score': '2.0', 'id': 863}, {'score': '1.0', 'id': 756}]

但是,我正在寻找一种对元素进行排序的方法,但只保留前 10 个字典并丢弃其他字典。 dicts 列表必须只有 10 个按高分排序的 dicts。

知道如何实现吗?

【问题讨论】:

  • newlist = sorted(l, key=lambda k: k['score'], reverse=True)[:10]?

标签: python list python-2.7 dictionary


【解决方案1】:

如果您的列表相当小,您可以对它们进行排序并通过切片获得前 10 名

时间:O(nlog n):n是原始列表中的项目数

l = [{'score': '4.0', 'id': 686}, {'score': '3.0', 'id': 55}, {'score': '2.0', 'id': 863}, {'score': '1.0', 'id': 756}]
newlist = sorted(l, key=lambda k: k['score'], reverse=True)[:10]
newlist

如果您有一个大列表,您可以每次都获得最大值并将其附加到您的列表中。如果元素数量很多,这将比排序更有效

时间:O(kn) : n 是原始列表中的项目数,您想要前 k 个项目

l = [{'score': '4.0', 'id': 686}, {'score': '3.0', 'id': 55}, {'score': '2.0', 'id': 863}, {'score': '1.0', 'id': 756}]
result = []
n = 10
for i in range(n):
    if len(l)<=0:break
    m = max(l, key=lambda k: k['score'])
    l.remove(m)
    result.append(m)
result

输出相同:

[{'id': 686, 'score': '4.0'},
 {'id': 55, 'score': '3.0'},
 {'id': 863, 'score': '2.0'},
 {'id': 756, 'score': '1.0'}]

总结

如果 k&lt;log(n) 做 max 方法,否则排序

【讨论】:

    【解决方案2】:

    您可以通过订阅和带有自定义键的 sorted() 方法来做到这一点:

    l = l[:10] # Overwrite l so it contains only the first 10 dicts
    
    def s(dct):
        return dct['score'] # Returns the score of the dict
    
    sorted(l,key=s) # Sort l with the key
    
    print(l)
    

    【讨论】:

      猜你喜欢
      • 2015-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 2016-12-24
      • 2020-05-06
      • 2015-06-14
      • 1970-01-01
      • 2013-06-20
      相关资源
      最近更新 更多