包含 relativedelta 对象的列表的聚合元素

Aggregate elements of a list containing relativedelta objects

我有一个列表 myList,其中包含 relativedelta 对象。我想添加所有这些 relativedeltas 对象。 我试过了:

sum(myList)

但它给出了 TypeError。

TypeError: unsupported operand type(s) for +: 'int' and 'relativedelta'

尽管可以使用 + Opeartor 添加 relativedelta 对象

代码不知何故:

from datetime import datetime
from dateutil.relativedelta import relativedelta

date1 = datetime(2018, 4, 9).date()
date2 = datetime(2019, 8, 18).date()
date3 = datetime(2014, 2, 1).date()
date4 = datetime(2018, 12, 30).date()

myList = []

rdelta1 = relativedelta(date2, date1)
myList.append(rdelta1)


rdelta2 = relativedelta(date4, date3)
myList.append(rdelta2)

print(sum(myList))

这是因为sum uses start value as 0.

>>> help(sum)
Help on built-in function sum in module builtins:

sum(iterable, /, start=0)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may    reject non-numeric types.

例如sum([1, 2])就是0 + 1 + 2

>>> sum([1, 2])
3

sum([1, 2], start=7)7 + 1 + 2

>>> sum([1, 2], start=7)
10

所以要解决这个问题,请使用一个项目(relativedelta 对象)作为 start 参数,并将其他所有内容保留在可迭代对象中。

from datetime import datetime
from dateutil.relativedelta import relativedelta

date1 = datetime(2018, 4, 9).date()
date2 = datetime(2019, 8, 18).date()
date3 = datetime(2014, 2, 1).date()
date4 = datetime(2018, 12, 30).date()

myList = []

rdelta1 = relativedelta(date2, date1)

rdelta2 = relativedelta(date4, date3)
myList.append(rdelta2)

print(sum(myList, rdelta1)) # so both start and items in `MyList` are `relativedelta` types.

使用减少

from datetime import datetime
from dateutil.relativedelta import relativedelta
from functools import reduce

date1 = datetime(2018, 4, 9).date()
date2 = datetime(2019, 8, 18).date()
date3 = datetime(2014, 2, 1).date()
date4 = datetime(2018, 12, 30).date()

myList = []

rdelta1 = relativedelta(date2, date1)
myList.append(rdelta1)


rdelta2 = relativedelta(date4, date3)
myList.append(rdelta2)

print(reduce(lambda x, y: x + y, myList))