【问题标题】:Removing of multilevel duplicated paths删除多级重复路径
【发布时间】:2020-05-05 19:59:38
【问题描述】:

我有一个形成树的产品列表(ID、产品名称、发票类型、对父 ID 的引用):

text = """
1,Product1,INVOICE_FEE,
3,Product3,INVOICE_FEE,
7,Product7,DEFAULT,
2,Product2,DEFAULT,7
4,Product4,DEFAULT,7
5,Product5,DEFAULT,2
"""

以下代码创建路径:

lines = [ l.strip() for l in text.strip().splitlines() ]
hierarchy = [ tuple(l.split(',')) for l in lines ]

parents = defaultdict(list)
for p in hierarchy:
    parents[p[3]].append(p)

def pathsMet(parents, node=''):
    childNodes = parents.get(node)
    if not childNodes:
        return [[]]
    paths = []
    for ID, productName, invoiceType, parentID in childNodes:
        for p in pathsMet(parents, ID):
            paths.append([productName] + p)
    return paths

作为结果的路径列表:

[['Product1'], ['Product3'], ['Product7', 'Product4'], ['Product7', 'Product2', 'Product5']]

可能是某些路径会重复的情况,例如对于列表:

text = """
7,Product7,DEFAULT,
2,Product2,DEFAULT,7
4,Product4,DEFAULT,7
5,Product4,DEFAULT,7
"""

将是(可能是多级嵌套路径重复):

[['Product7'], ['Product7', 'Product2'], ['Product7', 'Product4'], ['Product7', 'Product4']]

如何去除重复的路径,但路径内的顺序仍然正确?

【问题讨论】:

    标签: python recursion path duplicates


    【解决方案1】:
    paths = [['Product7'], ['Product7', 'Product2'], ['Product7', 'Product4'], ['Product7', 'Product4']]
    
    def remove_duplicates(paths):
        new_paths = []
        s = set()
        for path in paths:
            t = tuple(path)
            if t not in s:
                new_paths.append(path)
                s.add(t)
        return new_paths
    
    print(remove_duplicates(paths))
    

    打印:

    [['Product7'], ['Product7', 'Product2'], ['Product7', 'Product4']]
    

    将每个路径转换为元组并检查它是否已经在集合中(您不能将列表添加到集合中,因此我们将列表转换为元组)。如果不是,我们将路径添加到新的路径列表和集合中,否则我们知道它是重复路径。

    您实际上不需要单独的函数来删除重复项。你可以有一组路径,最初是空的,在你追加一个新路径之前,检查函数 remove_duplicates 正在做的类型:

    s = set()
    def pathsMet(parents, node=''):
        childNodes = parents.get(node)
        if not childNodes:
            return [[]]
        paths = []
        for ID, productName, invoiceType, parentID in childNodes:
            for p in pathsMet(parents, ID):
                path = [productName] + p
                t = tuple(path)
                if t not in s:
                    paths.append(path)
                    s.add(t)
        return paths
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2019-07-14
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多