2 回答
TA贡献1780条经验 获得超5个赞
这是基于您提供的代码,但如其他评论中所述,对于大列表,它的工作速度真的很慢。
new_records = []
for record in records:
new_id = record['id']
new_name = record['name']
new_dict = {'id':new_id, 'name': new_name}
if not any(new_record['id'] == new_id for new_record in new_records):
new_records.append(new_dict)
TA贡献1865条经验 获得超7个赞
您还可以通过使用一组已经“见过”的条目过滤数组来实现:
records = [{"id":123, "name":'Course A', "enrolled_date":'1st Feb'},
{"id":123, "name":'Course A', "enrolled_date":'1st Jan'},
{"id":456, "name":'Course B', "enrolled_date":'1st Jan'}]
seen = set()
new_dict = [d for d in records if not(d['id'] in seen or seen.add(d['id']))]
# {'id': 123, 'name': 'Course A', 'enrolled_date': '1st Feb'}
# {'id': 456, 'name': 'Course B', 'enrolled_date': '1st Jan'}
添加回答
举报