删除这两个功能之间的冗余



我觉得之间有一个重叠

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

在这种情况下,如何编写更少的代码?可以只写一个函数吗?我想添加一个bool作为参数,类似于START = True,然后写if-else语句,但我不知道它是否干净。

如果您想对此进行概括,可以传入访问器函数。有多种方法可以做到这一点,但一个简单的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'))

最新更新