简体   繁体   中英

Python - Comparing datetime object to next in a list

I'm looping through a list that has datetime objects stored and comparing the current element to next. I am having trouble assigning the next element to a variable.

Code:

for p in Monray:
    if (MonBool == False):
        MonBool = True
        MonStartTimeBlock = p
        MonFirstPro = p
        Nextone = Monray[p+1]

Error:

unsupported operand type(s) for +: 'datetime.datetime' and 'int'

Seems it is trying to add 1 int to a datetime object rather than accessing the element at "p+1".

What am i doing wrong?

p is the element, not its index, so you can't use p+1 to get the next element.

You can use zip() to pair up the elements of the list with a slice starting with the second element.

for first_day, next_day in zip(Monray, Monray[1:]):
    # code that uses the days

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