我想通过id删除重复元素,其中status == a。
我的计划:
所以我写了这段代码:
# Create list2 of all ids
def get_list_of_all_ids(lst):
ids = []
for i in lst:
for x in i:
if x == 'id':
ids.append(i['id'])
return ids
# Create list3 of duplicates ids
def get_list_of_duplicates_ids(lst):
return list(set([x for x in lst if lst.count(x) >= 2]))
# Remove from origin list elements where id in list3 and where status == 'a'
def remove_duplicates(lst_of_dcts, lst_of_ids):
new_list = lst_of_dcts
for i in lst_of_dcts:
if i['id'] in lst_of_ids and i['status'] == 'a':
new_list.remove(i)
return new_list, len(new_list)
def go(list_of_dicts):
return remove_duplicates(
list_of_dicts, get_list_of_duplicates_ids(
get_list_of_all_ids(
list_of_dicts)
)
)
print(go(lst))
输入:
lst = [{'id': 2, 'status': 'a'},
{'id': 1, 'status': 'a'},
{'id': 4, 'status': 'z'},
{'id': 2, 'status': 'c'},
{'id': 3, 'status': 'a'},
{'id': 1, 'status': 'b'},
{'id': 5, 'status': 'a'},
{'id': 0, 'status': 'g'},
{'id': 5, 'status': 'f'}]
我的期望:
([{'status':'z','id':4},
{'status':'c','id':2},
{'status':'a','id':3},
{'status':'b','id':1},
{'status':'g','id':0},
{'status':'f','id':5}], 6)
我得到了什么:
([{'status':'a','id':1},
{'status':'z','id':4},
{'status':'c','id':2},
{'status':'a','id':3},
{'status':'b','id':1},
{'status':'g','id':0},
{'status':'f','id':5}], 7)