如何以最Pythonic的方式合并两个返回元组列表的函数结果?
如何更Pythonic地合并多个检查函数的返回结果
我有两个函数,每个都返回Tuple[List[str], List[str]]类型的元组(包含problems和warnings列表)。目前用临时变量合并它们感觉繁琐,想找更Pythonic的实现,甚至一行代码的方案?
我不想合并这两个检查函数,因为它们负责项目完全不同的检查维度。
现有基础代码
from typing import Tuple, List import logging def check_this() -> Tuple[List[str], List[str]]: problems = [] warnings = [] # 执行检查逻辑填充列表 return problems, warnings def check_that() -> Tuple[List[str], List[str]]: problems = [] warnings = [] # 执行另一组检查逻辑填充列表 return problems, warnings def log_check_results(problems: List[str], warnings: List[str]): logging.error("\n".join(problems)) logging.warning("\n".join(warnings))
我的现有实现
problems, warnings = check_this() p, w = check_that() problems.extend(p) warnings.extend(w) log_check_results(problems, warnings)
我尝试过下面的写法,但可读性较差:
problems, warnings = zip(check_this(), check_that()) log_check_results([m for l in problems for m in l], [m for l in warnings for m in l])
更Pythonic的解决方案
方案1:用itertools.chain高效拼接(推荐)
借助itertools.chain可以优雅地合并多个列表,代码简洁且效率高:
from itertools import chain # 解构两个检查函数的返回值 (problems1, warnings1), (problems2, warnings2) = check_this(), check_that() # 用chain拼接后转成列表 log_check_results( list(chain(problems1, problems2)), list(chain(warnings1, warnings2)) )
方案2:循环批量合并(扩展性最强)
如果以后可能新增更多检查函数,这种写法最容易维护,可读性也很好:
all_problems = [] all_warnings = [] # 把所有检查函数的调用结果放到列表里循环 for prob_list, warn_list in [check_this(), check_that()]: all_problems += prob_list all_warnings += warn_list log_check_results(all_problems, all_warnings)
以后加新检查函数,只需要在列表里追加check_another()即可。
方案3:一行代码实现(简洁优先)
用sum结合空列表来合并子列表,适合检查函数数量少的场景:
log_check_results( sum((check_this()[0], check_that()[0]), []), sum((check_this()[1], check_that()[1]), []) )
注意:如果合并的列表非常大,sum的效率不如chain,但对于检查结果这类数据量不大的场景完全够用。
内容的提问来源于stack exchange,提问作者monsterbacke
相关产品推荐
相关产品推荐

