首页 > 解决方案 > 消除这两个功能之间的冗余?

问题描述

我觉得之间有冗余:

def _determine_nodes_with_no_predecessors(nodes:List[Node])->List[str]:
    """
    Given the list of nodes returns the identifiers of nodes that doesn't have any predecessor. 
    """
    nodes_ids_without_prdecessors = []
    for node in nodes:
        if not node.predecessors: 
            nodes_ids_without_prdecessors.append(node.id_)
    return nodes_ids_without_prdecessors

和这个:

def _determine_nodes_with_no_successors(nodes:List[Node])->List[str]:
    """
    Given the list of nodes returns the identifiers of nodes that doesn't have any successor. 
    """
    nodes_ids_without_successors = []
    for node in nodes:
        if not node.successors: 
            nodes_ids_without_successors.append(node.id_)
    return nodes_ids_without_successors

在这种情况下如何编写更少的代码?可以只写一个函数吗?我考虑过添加一个布尔值作为参数,比如START = True然后写在 if-else 语句中,但我不知道它是否干净。

标签: python

解决方案


如果你想概括这一点,你可以传入一个访问器函数。有多种方法可以做到这一点,但一个简单的 lambda 就足够了:

def _determine_nodes_with_no_using(nodes: List[Node], accessor: Callable[[Node], List[Node]])-> List[str]:
    """
    Given the list of nodes returns the identifiers of nodes that doesn't have any successor. 
    """
    nodes_ids_without = []
    for node in nodes:
        if not accessor(node): 
            nodes_ids_without.append(node.id_)
    return nodes_ids_without

然后

_determine_nodes_with_no_using(nodes, lambda node: node.predecessors)

_determine_nodes_with_no_using(nodes, lambda node: node.successors)

您还可以使用该operator模块

from operator import attrgetter

_determine_nodes_with_no_using(nodes, attrgetter('successors'))

_determine_nodes_with_no_using(nodes, attrgetter('predecessors'))

推荐阅读