我正在尝试编写一个脚本,其中列出了3个变量。
首先,请参阅我当前的脚本:
import datetime as dt
import pandas as pd
x = ['jhon doe', 'GX']
y = ['donald ted', 'GY']
Z = ['smith joe', 'GZ']
start_date = dt.datetime(2019, 4,12)
end_date = dt.datetime(2019, 4,21)
daterange = pd.date_range(start_date, end_date)
for date in daterange:
print(date)
我为此带来麻烦:
12/04/2019, jhone doe, GX
13/04/2019, donald ted, GY
14/04/2019, smith jhoe, GZ
15/04/2019, jhone doe, GX
16/04/2019, donald ted, GY
17/04/2019, smith jhoe, GZ
18/04/2019, jhone doe, GX
19/04/2019, donald ted, GY
14/04/2019, smith jhoe, GZ
21/04/2019, jhone doe, GX
很明显,如果您看到我的预期输出。
谁能告诉我该怎么做?上面给出了这三个变量。
我认为不需要为此写很多东西
答案 0 :(得分:2)
好像您在工具箱中缺少一个工具:from itertools import cycle
。
通过cycle
,您可以创建一个迭代器,该迭代器可以连续浏览列表。如果您点击列表的末尾,它将返回到开头。
from itertools import cycle
import datetime as dt
import pandas as pd
x = ['jhon doe', 'GX']
y = ['donald ted', 'GY']
z = ['smith joe', 'GZ']
r = (x, y, z)
pool = cycle(r)
start_date = dt.datetime(2019, 4,12)
end_date = dt.datetime(2019, 4,21)
daterange = pd.date_range(start_date, end_date)
for date in daterange:
curent_person = next(pool)
print('{}, {}, {}'.format(date.strftime('%d/%m/%Y'), curent_person[0], curent_person[1]))
输出:
12/04/2019, jhon doe, GX
13/04/2019, donald ted, GY
14/04/2019, smith joe, GZ
15/04/2019, jhon doe, GX
16/04/2019, donald ted, GY
17/04/2019, smith joe, GZ
18/04/2019, jhon doe, GX
19/04/2019, donald ted, GY
20/04/2019, smith joe, GZ
21/04/2019, jhon doe, GX
答案 1 :(得分:0)
我将使用模函数按一个周期(x,y,Z)打印它。
import datetime as dt
import pandas as pd
x = ['jhon doe', 'GX']
y = ['donald ted', 'GY']
Z = ['smith joe', 'GZ']
start_date = dt.datetime(2019, 4,12)
end_date = dt.datetime(2019, 4,21)
daterange = pd.date_range(start_date, end_date)
i=0
for date in daterange:
if i % 3 == 0:
print (date.strftime('%d/%m/%Y'), *x, sep=',')
elif i % 3 == 1:
print (date.strftime('%d/%m/%Y'), *y, sep=',')
else:
print (date.strftime('%d/%m/%Y'), *Z, sep=',')
i+=1
结果:
12/04/2019,jhon doe,GX
13/04/2019,donald ted,GY
14/04/2019,smith joe,GZ
15/04/2019,jhon doe,GX
16/04/2019,donald ted,GY
17/04/2019,smith joe,GZ
18/04/2019,jhon doe,GX
19/04/2019,donald ted,GY
20/04/2019,smith joe,GZ
21/04/2019,jhon doe,GX