3 回答
TA贡献1864条经验 获得超6个赞
您可以使用 来检查该条目是否重复。count
recipes = [
{'id': 1, 'public': True},
{'id': 1, 'public': False},
{'id': 2, 'public': False},
{'id': 3, 'public': True},
{'id': 3, 'public': False}
]
list = []
[list.append(r) for r in recipes if [i['id'] for i in recipes].count (r['id']) == 1 or r['public']]
return list
TA贡献1900条经验 获得超5个赞
这个答案有O(n)时间,希望它足够了:
ids={} # Use a set to check for dups
l=[] # Answer list
for i in recipes: # O(n) time
if i['id'] in ids:
if i['public']:
ids[i['id']]=i
else:
ids[i['id']]=len(l) # renumber the index for later O(1) use
# len(l) is a O(1) function, so no need to keep a counter
l.append(i)
抱歉,这不是一行,但我认为这是很好的做法:)
TA贡献1772条经验 获得超5个赞
您可以先根据键以相反的顺序对列表进行排序,以便所有条目都位于顶部。然后执行列表理解以按顺序过滤掉唯一值:'public''public': True'id'
recipes = [{'id': 1, 'public': True},
{'id': 1, 'public': False},
{'id': 2, 'public': False},
{'id': 3, 'public': True},
{'id': 3, 'public': False}]
recipes.sort(key = lambda r: r['public'], reverse=True)
recipes_unique = []
[recipes_unique.append(r) for r in recipes if
r['id'] not in [s['id'] for s in recipes_unique]]
display(recipes_unique)
这提供了所需的结果(如有必要,您当然可以再次排序):'id'
[{'id': 1, 'public': True},
{'id': 3, 'public': True},
{'id': 2, 'public': False}]
添加回答
举报