gpt4 book ai didi

Python如何根据日期创建子列表?

转载 作者:行者123 更新时间:2023-12-01 05:32:11 25 4
gpt4 key购买 nike

我有一个这样的列表:

my = [datetime.datetime(2013, 11, 12, 20, 22, 5),
datetime.datetime(2013, 11, 12, 20, 21, 27),
datetime.datetime(2013, 11, 12, 20, 20, 28),
datetime.datetime(2013, 11, 11, 18, 21, 27),
datetime.datetime(2013, 11, 11, 15, 21, 27),
datetime.datetime(2013, 11, 11, 11, 21, 27),
datetime.datetime(2013, 11, 10, 9, 21, 27),
datetime.datetime(2013, 11, 10, 19, 21, 27),
datetime.datetime(2013, 11, 10, 22, 21, 27),
datetime.datetime(2013, 11, 10, 20, 21, 27)]

我想按天创建列表到另一个列表中,我使用 [n].date() 来比较日期并加入它们,但我在绕圈子却没有得到它,请有人帮助我吗?

预期结果:

    days = [
[datetime.datetime(2013, 11, 12, 20, 22, 5), datetime.datetime(2013, 11, 12, 20, 21, 27), datetime.datetime(2013, 11, 12, 20, 20, 28)],
[datetime.datetime(2013, 11, 11, 18, 21, 27),datetime.datetime(2013, 11, 11, 15, 21, 27),datetime.datetime(2013, 11, 11, 11, 21, 27)],
[datetime.datetime(2013, 11, 10, 9, 21, 27),datetime.datetime(2013, 11, 10, 19, 21, 27),datetime.datetime(2013, 11, 10, 22, 21, 27),datetime.datetime(2013, 11, 10, 20, 21, 27)]
]

尝试失败:

In [152]: fecha = None
.....: dia = []
.....: days = []
.....: for i in my:
.....: if fecha:
.....: if i.date() == fecha:
.....: dia.append(i)
.....: else:
.....: days.append(dia)
.....: fecha = i.date()
.....: else:
.....: fecha = i.date()

谢谢

最佳答案

使用itertools.groupby并使用key = datetime.date()进行分组:

.date()datetime 对象上返回 date 对象,我们可以使用它来对列表中的项目进行分组:

>>> my[0].date()
datetime.date(2013, 11, 12)

演示:

>>> from pprint import pprint
>>> from itertools import groupby
>>> pprint([list(g) for k, g in groupby(my, key=lambda x:x.date())])
[[datetime.datetime(2013, 11, 12, 20, 22, 5),
datetime.datetime(2013, 11, 12, 20, 21, 27),
datetime.datetime(2013, 11, 12, 20, 20, 28)],
[datetime.datetime(2013, 11, 11, 18, 21, 27),
datetime.datetime(2013, 11, 11, 15, 21, 27),
datetime.datetime(2013, 11, 11, 11, 21, 27)],
[datetime.datetime(2013, 11, 10, 9, 21, 27),
datetime.datetime(2013, 11, 10, 19, 21, 27),
datetime.datetime(2013, 11, 10, 22, 21, 27),
datetime.datetime(2013, 11, 10, 20, 21, 27)]]

如果键尚未按日期排序,则使用 collections.defaultdict(list) 并使用 datetime.date() 作为键。

关于Python如何根据日期创建子列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19965113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com