JupyterLab 上的日期循环问题和列表删除问题
A date loop problem and list remove problem on JupyterLab
大家好,我在JupyterLab上遇到了日期循环问题,问题如附图:
很奇怪B的红圈竟然和A的红圈一样显示,为什么第6周不见了?
和“如果 [5、6] 中的 d.weekday():dates.remove(d)”。应该去掉5和6,怎么会有4/3和4/10?
我重启了内核,结果还是一样。太棒了...
您不应在遍历列表时修改列表 dates
。请检查 Strange result when removing item from a list while iterating over it 了解更多详情。
要删除周六或周日的日期,试试这个:
import pandas as pd
from datetime import datetime
from datetime import timedelta
d = datetime(2022, 4, 1)
dates = [d + timedelta(days=idx) for idx in range(10)]
for d in dates:
print(f'{d.date()} {d.weekday()}' )
new_dates = dates.copy()
for d in dates:
if d.weekday() in [5, 6]:
new_dates.remove(d)
print("Removed Saturdays and Sundays!")
for d in new_dates:
print(f'{d.date()} {d.weekday()}' )
这给出:
2022-04-01 4
2022-04-02 5
2022-04-03 6
2022-04-04 0
2022-04-05 1
2022-04-06 2
2022-04-07 3
2022-04-08 4
2022-04-09 5
2022-04-10 6
Removed Saturdays and Sundays!
2022-04-01 4
2022-04-04 0
2022-04-05 1
2022-04-06 2
2022-04-07 3
2022-04-08 4
很奇怪B的红圈竟然和A的红圈一样显示,为什么第6周不见了?
和“如果 [5、6] 中的 d.weekday():dates.remove(d)”。应该去掉5和6,怎么会有4/3和4/10?
我重启了内核,结果还是一样。太棒了...
您不应在遍历列表时修改列表 dates
。请检查 Strange result when removing item from a list while iterating over it 了解更多详情。
要删除周六或周日的日期,试试这个:
import pandas as pd
from datetime import datetime
from datetime import timedelta
d = datetime(2022, 4, 1)
dates = [d + timedelta(days=idx) for idx in range(10)]
for d in dates:
print(f'{d.date()} {d.weekday()}' )
new_dates = dates.copy()
for d in dates:
if d.weekday() in [5, 6]:
new_dates.remove(d)
print("Removed Saturdays and Sundays!")
for d in new_dates:
print(f'{d.date()} {d.weekday()}' )
这给出:
2022-04-01 4
2022-04-02 5
2022-04-03 6
2022-04-04 0
2022-04-05 1
2022-04-06 2
2022-04-07 3
2022-04-08 4
2022-04-09 5
2022-04-10 6
Removed Saturdays and Sundays!
2022-04-01 4
2022-04-04 0
2022-04-05 1
2022-04-06 2
2022-04-07 3
2022-04-08 4