Python 如何在有条件的列表理解中使用多个 for 循环
Python How to use multiple for loops in list comprehension with conditions
我仍在处理下面的代码,代码运行良好。我正在尝试减少代码行数。
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)
此代码returns2016年第一个月有5个周五、周六、周日; 2020年最后一个月也是一样,有多少个月满足这个条件。
所以输出是:('Jan', 'May', 5)
x 变量的注释部分是我尝试过的 returns 0 和 None(else 语句的原因)
你的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)
我修复的一些小问题:
- 直接在 list comp 中获取
month_abbr
而不是在末尾获取两次
-1
本身就是一个有效的索引
- 两个weekday-checks是多余的
我仍在处理下面的代码,代码运行良好。我正在尝试减少代码行数。
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)
此代码returns2016年第一个月有5个周五、周六、周日; 2020年最后一个月也是一样,有多少个月满足这个条件。
所以输出是:('Jan', 'May', 5)
x 变量的注释部分是我尝试过的 returns 0 和 None(else 语句的原因)
你的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)
我修复的一些小问题:
- 直接在 list comp 中获取
month_abbr
而不是在末尾获取两次 -1
本身就是一个有效的索引- 两个weekday-checks是多余的