[英]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".似乎它试图将 1 个 int 添加到 datetime 对象,而不是访问“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. p
是元素,而不是它的索引,因此您不能使用p+1
来获取下一个元素。
You can use zip()
to pair up the elements of the list with a slice starting with the second element.您可以使用
zip()
将列表元素与从第二个元素开始的切片配对。
for first_day, next_day in zip(Monray, Monray[1:]):
# code that uses the days
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.