Python 对字典列表进行切片以保留一系列项
我有一张这样的单子,但要大得多:Python 对字典列表进行切片以保留一系列项,python,list,python-2.7,dictionary,Python,List,Python 2.7,Dictionary,我有一张这样的单子,但要大得多: 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个字典,而丢弃其他字典单子列表中必须只有10个单子按
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个字典,而丢弃其他字典单子列表中必须只有10个单子按较高的分数排序。
你知道如何做到这一点吗?如果你有一个相当小的列表,你可以对它们进行排序,并通过切片的方式获得前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
摘要:
如果
k您可以通过订阅和带有自定义键的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)
newlist=sorted(l,key=lambda k:k['score'],reverse=True)[:10]
?
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)