gpt4 book ai didi

python - 在按日期的嵌套列表中按时间对元素进行分组?

转载 作者:行者123 更新时间:2023-12-04 20:26:40 28 4
gpt4 key购买 nike

我有一个具有这种结构的嵌套列表:

mylist = [

[
['Bob', 'Male', '2019-12-10 9:00'],
['Sally', 'Female', '2019-12-10 15:00']
],

[
['Jake', 'Male', '2019-12-12 9:00'],
['Ally', 'Female', '2019-12-12 9:30'],
['Jamal', 'Male', '2019-12-12 15:00']
],

[
['Andy', 'Male', '2019-12-13 15:00'],
['Katie', 'Female', '2019-12-13 15:30']
]

]

目前,这份主名单 mylist按日期组织。包含同一天的所有元素(即 2019-12-12、2019-12-13...)嵌套在一起。

我想将此嵌套更进一步,并在该日期嵌套组内创建另一个嵌套组。这一次,我想按时间安排它们。我想将所有在 9 小时有标签的人组合在一起,并将在 15 小时有标签的人组合在一起。

所以,我试图得到这个输出:
newlist = [

[
[
['Bob', 'Male', '2019-12-10 9:00']
],
[
['Sally', 'Female', '2019-12-10 15:00']
]
],


[
[
['Jake', 'Male', '2019-12-12 9:00'],
['Ally', 'Female', '2019-12-12 9:30'],
],
[
['Jamal', 'Male', '2019-12-12 15:00']
]
],


[
[
['Andy', 'Male', '2019-12-13 15:00'],
['Katie', 'Female', '2019-12-13 15:30']
]
]


]

基于对 this 的公认答案问题,我修改并尝试使用以下代码,但没有用。
newdict = defaultdict(list)

for data in mylist:
for datum in data:
_, _, time = datum
_, date_time = time.split(" ")
_, hour_minute = date_time.split(":")
newdict[hour_minute].append(datum)

newlist = list(newdict.values())
print(newlist)

--------------------------------------------------------------------------------------------------------
Output:

[
[
['Bob', 'Male', '2019-12-10 9:00'],
['Sally', 'Female', '2019-12-10 15:00'],
['Jake', 'Male', '2019-12-12 9:00'],
['Ally', 'Female', '2019-12-12 9:30'],
['Jamal', 'Male', '2019-12-12 15:00'],
['Andy', 'Male', '2019-12-13 15:00'],
['Katie', 'Female', '2019-12-13 15:30']
]
]

我也做了很多在线搜索,但找不到任何解决方案。有谁知道如何做到这一点?另外,请记住,我是编程新手,所以请尽量使答案/解释尽可能简单。谢谢!

最佳答案

如果它们已经排序,我们可以使用 groupby 具有隔离小时以将它们分组的功能:

from itertools import groupby


def f(l):
return l[2].split(" ")[1].split(":")[0]

newlist = [[list(g) for _, g in groupby(subl, f)] for subl in mylist]

结果是
[
[
[
['Bob', 'Male', '2019-12-10 9:00']
],
[
['Sally', 'Female', '2019-12-10 15:00']
]
],
[
[
['Jake', 'Male', '2019-12-12 9:00'],
['Ally', 'Female', '2019-12-12 9:30']
],
[
['Jamal', 'Male', '2019-12-12 15:00']
]
],
[
[
['Andy', 'Male', '2019-12-13 15:00'],
['Katie', 'Female', '2019-12-13 15:30']
]
]
]

关于python - 在按日期的嵌套列表中按时间对元素进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59381053/

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