简体   繁体   中英

Generate Date List of Lists

I would like to generate a list of lists which each sublist containing a date between two dates. I am eventually going to append values to each sublist.

My code:

from datetime import date, datetime, timedelta

def date_increments(start, end, delta):
    curr = start
    while curr < end:
        yield curr
        curr += delta

my_dates = []
row=0
for result in date_increments(date(2014, 10, 10), date(2014, 10, 12), timedelta(days=1)):
    my_dates[row][0] = result
    row += 1

print my_dates

Error:

my_dates[row][0] = result
IndexError: list assignment index out of range

Desired output:

[[date(2014, 10, 10)],[date(2014, 10, 11)],[date(2014, 10, 12)]]

Just use append :

my_dates.append([result])

You don't even need to use row .

Also, use:

while curr <= end:

in order to have end in the final list.

And for an even shorter solution, use:

my_dates = [[res] for res in date_increments(date(2014, 10, 10), date(2014, 10, 12), timedelta(days=1))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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