python - 如何避免 if/else 语句中的重复代码?

标签 python algorithm python-3.x

我在 if/else 语句中有两个完全相同的逻辑:

    if alert.get('comment_time_created') is None:
 here-> args = {'is_comment_visible': 1, 'comment_time_created': current_comment_time}
        await self._db_alert.update_alert(alert['alert_id'], **args)
    else:
        first_comment_time_creation = datetime.strptime(alert['comment_time_created'], '%Y-%m-%dT%H:%M:%SZ')
        current_comment_time = datetime.strptime(current_comment_time, '%Y-%m-%dT%H:%M:%SZ')
        if current_comment_time > first_comment_time_creation:
            await self._db_alert.update_alert(alert['alert_id'], is_comment_visible=1)
        else:
 here->     args = {'is_comment_visible': 1, 'comment_time_created': current_comment_time}
            await self._db_alert.update_alert(alert['alert_id'], **args)

有没有办法把这个逻辑做一次?

最佳答案

您似乎在每种情况下都执行 await 行,只是您的 kwargs 在您没有 comment_time_created arg 的地方改变了一个特定条件。这可以简化为:

args = {'is_comment_visible': 1}
if alert.get('comment_time_created') is None:
    args['comment_time_created'] = current_comment_time
else:
    first_comment_time_creation = datetime.strptime(alert['comment_time_created'], '%Y-%m-%dT%H:%M:%SZ')
    current_comment_time = datetime.strptime(current_comment_time, '%Y-%m-%dT%H:%M:%SZ')
    if current_comment_time <= first_comment_time_creation:
        args['comment_time_created']= current_comment_time

await self._db_alert.update_alert(alert['alert_id'], **args)

关于python - 如何避免 if/else 语句中的重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46773511/

相关文章:

python - 如何在没有 pip 或 virtualenv 的情况下安装 python 包

python - 逐字书写文本

algorithm - 约束到水平/垂直轴的边界椭圆

python - 从文本文件中读取特定行作为 numpy 数组

python - 数据帧索引

algorithm - 亚马逊采访 : Min stack

java - Java 中的二重积分和期望值蒙特卡洛方法

python - 计算时间复杂度为 O(nlogn) 的列表中的出现次数

python - 是否有在 __init__ 方法中定义变量的最佳实践

python - 对包含列表作为值的字典列表进行排序