首页 > 解决方案 > 如何检查列表中的元素(b)是否包含同一列表中的元素(a)。比删除元素 (a)

问题描述

如果它在另一个元素中,我需要删除它

    def c_counter_check(new_filters):         #new filters is an list
        for i in new_filters_splited[:]:
            index = new_filters_splited.index(i) #get index of an i
            mylist = new_filters_splited[:index] + new_filters_splited[index + 1:] # create a compare list without i
            for a in mylist[:]:
                if a.__contains__(i):    #check if an element from mylist contains an i
                    new_filters_splited.remove(i)      #if yes than remove i from new_filters_splited
        return new_filters_splited

例如,如果我的列表是['a', 'ab', 'ac', 'ab', 'abac']我需要删除'a' and 'ab' and 'abac' and 'ac'的,结果应该只是['a']

标签: pythonlistloopsfor-loopnested-loops

解决方案


def deduplicate(list_to_deduplicate):
    elems = set()
    rest = []
    for el in list_to_deduplicate:
        if el not in elems:
            elems.add(el)
            rest.append(el)
    return rest

def c_counter_check(list_to_filter):
    res = []
    lst_s = deduplicate(list_to_filter)
    for index, attribute in enumerate(lst_s):
        mylist = lst_s[:index] + lst_s[index + 1:]
        global checker
        checker = 0
        if any(attribute in b for b in mylist):
            res.append(attribute)
            for b in mylist:
                if attribute.__contains__(b):
                    res.remove(attribute)
                    break
        else:
            if not any(attribute in r for r in res):
                res.append(attribute)
                if any(b in attribute for b in mylist):
                    res.remove(attribute)
    return res

这是完整的工作解决方案感谢来自 discord 的 @ConfusedReptile 创建deduplicate函数


推荐阅读