python - 消除这两个功能之间的冗余?
问题描述
我觉得之间有冗余:
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 语句中,但我不知道它是否干净。
解决方案
如果你想概括这一点,你可以传入一个访问器函数。有多种方法可以做到这一点,但一个简单的 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'))
推荐阅读
- python - 如何在离散图形 AMD GPU 上运行 Python 脚本?
- intershop - 如何访问单个计算产品行项目的所有子组计算项目
- swift - 如何将数据转换为 UnsafeMutablePointer
? - javascript - 如何将 csv 数据保存到 nodejs 中的 .csv 文件中?
- oracle - 从 Kotlin 微服务获取 Oracle sql 的数据得到重复的结果
- typescript - 键入 svelte $store 变量
- c++ - Microsoft Visual C++ Redistributable 包提取的 dll 文件是什么?
- amazon-web-services - 手动将缺失值发送到 Amazon Forecast
- mysql - 在 SQL 中选择发送者和接收者之间的最后一条消息
- javascript - 如何在自定义钩子中测试 useEffect?