将列表的元素链接为

2024-09-27 00:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似于这样的python列表,例如:

[Product(parent=tube,child=spokes), Product(parent=bicycle, child=wheel), Product(parent=wheel,child=tube)]

其中Product是一个python类,有两个成员parentchild。你知道吗

Products可以以任何顺序出现在列表中。你知道吗

实现以下目标最有效的方法是什么:

Given an input spokes for example , return the `root of the tree` , bicycle in this case.

到目前为止,我尝试过的是:当产品每次出现的顺序不同时,循环不能给出正确的结果。你知道吗


Tags: the方法child目标列表顺序成员product
2条回答

您不需要写下您可以应用于数据的假设有多强(如果它始终是正确的树)。所以我的代码检查了一些条件,使其不在无限循环中。你知道吗

def find_root(pr_list, child):
    if len(pr_list) == 0:
        return None
    child_translate_dict = {x.child: x for x in pr_list}
    potential_root = child
    count = 0
    while count < len(pr_list):
        if potential_root not in child_translate_dict:
            return potential_root
        else:
            potential_root = child_translate_dict[potential_root].parent
            count += 1 
    return None

和更短的版本

def find_root(pr_list, child):
    child_translate_dict = {x.child: x for x in pr_list}
    while child in child_translate_dict:
        child = child_translate_dict[potential_root].parent
    return child

以下是针对您的问题的伪代码:

def recursiveRootFinder(child,theList):
    for(i in theList):
        if (i.child==child):
            child=recursiveRootFinder(i.parent,theList)
    return child  

可以使用lambda定义在一行中实现它,如下所示:

lambda child,theList: recursiveRootFinder(i.parent,theList) for i in list if i.child==child if [1 for i in list if i.child==child]!=[] else child

相关问题 更多 >

    热门问题