【问题标题】:Python How to use multiple for loops in list comprehension with conditionsPython如何在带有条件的列表理解中使用多个for循环
【发布时间】:2020-09-10 14:56:45
【问题描述】:

我仍在处理下面的代码,代码运行良好。我正在尝试减少代码行数。

import calendar as c
def solve(first, last):
    weekends = []
    # x = [weekends.append(m) if c.weekday(y,m,1) == 4 and c.weekday(y,m,31) == 6 else 0 for m in [1,3,5,7,8,10,12] for y in range(first,last+1)]
    for y in range(first,last+1):
        for m in [1,3,5,7,8,10,12]:
            if c.weekday(y,m,1) == 4 and c.weekday(y,m,31) == 6:
                weekends.append(m)
    return c.month_abbr[weekends[0]], c.month_abbr[weekends[len(weekends)-1]], len(weekends)

调用时:solve(2016,2020)

此代码返回 2016 年的第一个月,它有 5 个星期五、星期六、星期日;与 2020 年最后一个月相同,以及满足此条件的月份数。

所以输出是:('Jan', 'May', 5)

x 变量的注释部分是我尝试过的,它返回 0 和 None(因为 else 语句)

【问题讨论】:

    标签: python python-3.x for-loop list-comprehension


    【解决方案1】:

    x = ... 中的语句顺序有点乱;您的 if 应该过滤要包含的值,而不是要使用的两个替代值中的哪一个。而且:不要在列表推导中使用append 来追加到另一个列表!相反,列表推导本身应该是您的结果。

    def solve(first, last):
        weekends = [c.month_abbr[m] for y in range(first,last+1)
                                    for m in [1,3,5,7,8,10,12]
                                    if c.weekday(y,m,1) == 4]
        return weekends[0], weekends[-1], len(weekends)
    

    我修正的一些小问题:

    • 直接在列表组合中获取month_abbr,而不是最后两次
    • -1 本身就是一个有效的索引
    • 两个工作日检查是多余的

    【讨论】:

    • 感谢您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2016-05-29
    • 2021-08-17
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    相关资源
    最近更新 更多