我有以下清单;
[
{
"title": "title1",
"url": "https://myurl/entry/1",
"author": "john",
"count": 5
},
{
"title": "title1",
"url": "https://myurl/entry/2",
"author": "marry",
"count": 19
},
{
"title": "title1",
"url": "https://myurl/entry/1",
"author": "john",
"count": 45
},
{
"title": "title2",
"url": "https://myurl/entry/5",
"author": "jane",
"count": 34
}
]
我试图将此列表添加到json文件中,但我只想添加唯一值。如您所见,我的第一项和第三项的标题,URL和作者完全相同。唯一的区别是计数。无论它们的数量如何,我只想附加这两项中的一项。如果标题,URL和作者相同,请先附加然后忽略其他内容。最终的json文件将按计数的降序排序。
我尝试下面的代码,但它仍附加非唯一值。
newlist=[]
[newlist.append(x) for x in originallist if x not in newlist]
newlist = sorted(newlist, key=lambda k: k.get('count', 0), reverse=True)
ofile = "final.json"
with open(ofile, 'w') as outfile:
json.dump(newlist, outfile,indent=2)
我的最终json文件应如下所示。按计数编号排序,仅插入唯一值。
[
{
"title": "title2",
"url": "https://myurl/entry/5",
"author": "jane",
"count": 34
},
{
"title": "title1",
"url": "https://myurl/entry/2",
"author": "marry",
"count": 19
},
{
"title": "title1",
"url": "https://myurl/entry/1",
"author": "john",
"count": 7
}
]
知道我在这里缺少什么吗?