这是我的清单:
my_list = [{'id': '5927'}, {'id': '5931'}, {'id': '5929'}, {'id': '5930'}, {'id': '5928'}, {'id': '5929'}, {'id': '5930'}]
如果
id
的值重复,我将删除。
我尝试这样做,但它只删除一个ID:
my_list = [{'id': '5927'}, {'id': '5931'}, {'id': '5929'}, {'id': '5930'}, {'id': '5928'}, {'id': '5929'}, {'id': '5930'}]
remove_duplicates = []
for the_id in my_list:
if the_id['id'] not in remove_duplicates:
remove_duplicates.append({'id': the_id['id']})
else:
my_list.remove({'id': the_id['id']})
my_list
remove_duplicates
我用谷歌搜索并尝试了不同的方法,但没有一个按预期工作。
预期输出是:
my_list = [{'id': '5927'}, {'id': '5931'}, {'id': '5929'}, {'id': '5930'}, {'id': '5928'}]
我们可以使用
set
来保留我们已经看到的 id:
my_list = [{'id': '5927'}, {'id': '5931'}, {'id': '5929'}, {'id': '5930'}, {'id': '5928'}, {'id': '5929'}, {'id': '5930'}]
unique_ids = set()
remove_duplicates = []
for item in my_list:
if item['id'] not in unique_ids:
unique_ids.add(item['id'])
remove_duplicates.append(item)
print(remove_duplicates)