【发布时间】:2020-07-04 16:08:35
【问题描述】:
我正在尝试制作的程序的主要目的是能够填写(插入)具有价格和日期时间的对象列表,如果缺少月份,如果有,插入重复对象,但月份正确,该特定月份的最后一天价格相同(无变化)
这是一个例子。
假设列表dateprices 在程序的其他地方动态填充了对象。每个项目 (datePriceObj) 都有变量:date 是日期时间对象,price 是该日期的价格(假设它是亚马逊上产品的价值或其他东西,没关系.)
我想要达到的效果如下所示:
创建下面对象的类
class DatePriceCreator():
def __init__(self, datetimeObj, priceFloat):
self.date = datetimeObj
self.price = priceFloat
我目前所拥有的,需要更改以便正确填写月份:
datePrices = [datePriceObj, datePriceObj, datePriceObj, datePriceObj, datePriceObj]
# datePrices[0].date is equal to 25th October 2019 (this is a datetime object)
# datePrices[1].date is equal to 23rd November 2019 (this is a datetime object)
# datePrices[2].date is equal to 26th February 2020 (this is a datetime object)
# datePrices[3].date is is equal to 26th March 2020 (this is a datetime object)
# datePrices[4].date is equal to 15th May 2020 (this is a datetime object)
# datePrices[0].price is equal to 1000.0 (this is a float)
# datePrices[1].price is equal to 1056.0 (this is a float)
# datePrices[2].price is equal to 1700.0 (this is a float)
# datePrices[3].price is equal to 1750.0 (this is a float)
# datePrices[4].price is equal to 2007.0 (this is a float)
预期输出:
# Expected Output:
datePrices = [datePriceObj, datePriceObj, datePriceObj, datePriceObj. datePriceObj, datePriceObj, datePriceObj, datePriceObj]
# datePrices[0].date is equal to 25th October 2019 (this is a datetime object)
# datePrices[1].date is equal to 23rd November 2019 (this is a datetime object)
# datePrices[2].date is equal to 31st December 2019 (this is a datetime object)
# datePrices[3].date is equal to 31st January 2020 (this is a datetime object)
# datePrices[4].date is equal to 26th February 2020 (this is a datetime object)
# datePrices[5].date is is equal to 26th March 2020 (this is a datetime object)
# datePrices[6].date is is equal to 30th April 2020 (this is a datetime object)
# datePrices[7].date is equal to 15th May 2020 (this is a datetime object)
# datePrices[0].price is equal to 1000.0 (this is a float)
# datePrices[1].price is equal to 1056.0 (this is a float)
# datePrices[2].price is equal to 1056.0 (this is a float)
# datePrices[3].price is equal to 1056.0 (this is a float)
# datePrices[4].price is equal to 1700.0 (this is a float)
# datePrices[5].price is equal to 1750.0 (this is a float)
# datePrices[6].price is equal to 1750.0 (this is a float)
# datePrices[7].price is equal to 2007.0 (this is a float)
正如您在预期输出中看到的那样,新对象已填充到列表中,这些新对象包含填充月份的日期、该月的最后一天以及价格和之前的一样。
我面临的问题是如何做到这一点,所以无论年份是什么,它总是有下个月。这显示在 datePrices[2] 和 datePrices[3] 的预期输出中,它识别出年份已更改。我不知道该怎么做。可能使用某种 while 循环来继续创建对象并插入到列表中,直到 datePrices[x+1].date.month - 1 等于 datePrices[x].date.month,但这只有在 datePrices[x].date.month is <= 11 时才有效。如果是12,则下个月必须是13,但没有第13个月。
我是这方面的初学者,想知道在不使用太多条件的情况下最有效的解决方案是什么,除非绝对必要。
【问题讨论】:
标签: python loops datetime oop iterator