python - 在 Python 中使用可选的 For 子句遵守 DRY 的最佳方式

标签 python data-structures iteration

我有一个方法,涉及一个很长的 if/elif block 来转换所提供对象的属性。我想避免使用两种方法。如果该方法可以采用可迭代列表或不可迭代的单个对象,那么如果该对象不可迭代,如何使 if/elif block 仍然执行?

现在我的代码基本上如下所示:

def convert_orders(orders, orderid=None):
    """Converts certain fields of an order object to readable and/or indexable values"""

    status = None
    color = None
    order = None
    converted = []

    if not orders:
        order = session.query(Order).filter(Order.orderid == orderid)

    for order in orders:
        # convert order status to a string and give it a color for the tables
        if order.status == 0:
            status = 'In Progress'
            color = QColor(150, 255, 250)
        elif order.status == 1:
            status = 'Ready'
            color = QColor(60, 255, 75)

# elif continues below for another 70+ lines, converting other attributes.

如果 orders 作为列表提供,但此方法也可以采用 orderid (整数),我如何仅使用一个 elif block 来转换任一类型,具体取决于是在哪一个上提供的?该方法可以使用一种类型或另一种类型来调用,但绝不能同时使用两种类型。

最佳答案

if not orders:
    ...
    orders = (order,)

关于python - 在 Python 中使用可选的 For 子句遵守 DRY 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498152/

相关文章:

algorithm - 如何为 HashSet/HashMap 实现哈希函数

sorting - 带重音符号的字符串键的排序结构

c - 大数据集散列和C实现

python - 从交替的侧面循环列表

python - RabbitMQ:Pika:消费时添加超时

python - 如何反导入 Python 模块?

python - Key=Val 使用正则表达式匹配

python - Pandas - 从列中的 float 中删除字符串

javascript - 我正在寻找检查树是否对称的迭代解决方案

python - 计算多个并行数组的最优雅/高效/Pythonic 方法?