Python foor循环在列表中添加随机日期

时间:2019-04-24 04:01:47

标签: python python-3.x

我有一个3列表,该列表会根据日期前后的日期进行平均打印, 例如: 列表 ylist 列表 列表 ylist等.....

这是我当前的脚本:

import datetime as dt
import pandas as pd

start_date = dt.datetime(2019, 4,12)
end_date = dt.datetime(2019, 4,21)
daterange = pd.date_range(start_date, end_date)

XLIST = ['401', 'Pabolo Picasso', '402', 'Justin TED', '303', 'Ariana Great']
YLIST = ['201', 'Donald Ted', '202', 'Einastain', '203', 'Hillary Cloud']
ZLIST = ['301', 'Theresa March', '302', 'Jullian Ass Bad', '303', 'Messi Bro']

i = 0
for date in daterange:
    if i % 3 == 0:
        print(XLIST)
    elif i % 3 == 1:
        print(YLIST)
    else:
        print(ZLIST)
    i+=1

上面的脚本输出是:

['401', 'Pabolo Picasso', '402', 'Justin TED', '303', 'Ariana Great']
['201', 'Donald Ted', '202', 'Einastain', '203', 'Hillary Cloud']
['301', 'Theresa March', '302', 'Jullian Ass Bad', '303', 'Messi Bro']
['401', 'Pabolo Picasso', '402', 'Justin TED', '303', 'Ariana Great']
['201', 'Donald Ted', '202', 'Einastain', '203', 'Hillary Cloud']
['301', 'Theresa March', '302', 'Jullian Ass Bad', '303', 'Messi Bro']
['401', 'Pabolo Picasso', '402', 'Justin TED', '303', 'Ariana Great']
['201', 'Donald Ted', '202', 'Einastain', '203', 'Hillary Cloud']
['301', 'Theresa March', '302', 'Jullian Ass Bad', '303', 'Messi Bro']
['401', 'Pabolo Picasso', '402', 'Justin TED', '303', 'Ariana Great']

并且输出不满足我要求:

我也需要在列表中显示日期:

这是我的预期输出:

[12/04/2019, '401', 'Pabolo Picasso', '402', 'Justin TED', '303', 'Ariana Great']
[13/04/2019, '201', 'Donald Ted', '202', 'Einastain', '203', 'Hillary Cloud']
[14/04/2019, '301', 'Theresa March', '302', 'Jullian Ass Bad', '303', 'Messi Bro']
[15,04/2019,'401', 'Pabolo Picasso', '402', 'Justin TED', '303', 'Ariana Great']
[16/04/2019, '201', 'Donald Ted', '202', 'Einastain', '203', 'Hillary Cloud']
[17/04/2019, '301', 'Theresa March', '302', 'Jullian Ass Bad', '303', 'Messi Bro']
[18/04/2019, '401', 'Pabolo Picasso', '402', 'Justin TED', '303', 'Ariana Great']
[19/04/2019, '201', 'Donald Ted', '202', 'Einastain', '203', 'Hillary Cloud']
[20/04/2019, '301', 'Theresa March', '302', 'Jullian Ass Bad', '303', 'Messi Bro']
[21/04/2019, '401', 'Pabolo Picasso', '402', 'Justin TED', '303', 'Ariana Great']

指南:如果您看到脚本和预期的输出,那么您将不会看到我正在寻找的东西以及我已停止的地方。 非常感谢

1 个答案:

答案 0 :(得分:0)

在循环中创建一个新列表,这样就不会修改原始列表:

for date in daterange:
    if i % 3 == 0:
        print([str(date)] + XLIST)
    elif i % 3 == 1:
        print([str(date)] + YLIST)
    else:
        print([str(date)] + ZLIST)
    i+=1

您可能需要格式化日期,而不仅仅是调用str。 无论如何,这里有live example