简体   繁体   English

如何从日期列表中删除周末?

[英]How to remove Weekends from a datelist?

I am using the following code to remove weekends from a datelist:我正在使用以下代码从日期列表中删除周末:

def clear_weekends(date_list):
for i, e in enumerate(date_list):
    if e.isoweekday() == 7: 
        del date_list[i]
for i, e in enumerate(date_list):
    if e.isoweekday() == 6: 
        del date_list[i]
return date_list

For some reason though, it doesn't work and apparently random saturdays are not removed.但由于某种原因,它不起作用,显然随机星期六没有被删除。 Before, I had both saturday and sunday in the same for loop with the same if-statement.以前,我在同一个 for 循环中使用相同的 if 语句在周六和周日。 Then, it seemed not to delete any saturdays at all.然后,它似乎根本没有删除任何星期六。

Does anybody know what is going on?有人知道发生了什么吗?

For a larger list, I can use对于更大的列表,我可以使用

for e in clear_weekends(datelist):
if e.isoweekday() == 6: print("Saturday!")
elif e.isoweekday() == 7: print("Sunday!")

and I will still receive varying amount of saturdays (never sundays though).而且我仍然会收到不同数量的星期六(虽然从来没有星期天)。

Any help is appreciated!任何帮助表示赞赏!

It's generally a bad idea to modify a list while you're iterating over it.在迭代列表时修改列表通常不是一个好主意。 You should delete them with a filter expression instead.您应该使用过滤器表达式来删除它们。 Maybe a list comprehenseion?也许是一个列表理解?

def clear_weekends(date_list):
    return [d for d in date_list if d.isoweekday() < 6]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM