按特定条件从字典列表中删除重复项

时间:2016-05-18 14:47:27

标签: python python-3.x

我想通过id删除重复元素,其中status == a。

我的计划:

  1. 输入列表 - list1
  2. 从list1
  3. 创建所有ID的list2
  4. 从list2
  5. 创建重复项ID列表3
  6. 从原始list1元素中删除list3中的id和where =='a'
  7. 所以我写了这段代码:

    # 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)
    

0 个答案:

没有答案