gpt4 book ai didi

python - 嵌套的 defaultdict(list) 分组

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

我有一组结果行,我试图将它们分组为两层嵌套 [{key: value[{key:value[]}]}]。这些值在顶级键中是非唯一的。

我一直在尝试使用 defaultdict,但由于非唯一性,在两个级别上都没有成功分组。迭代数据可能更好,但我也没有成功。

起始数据:

data = 
[{'Name': 'Bob', 'Time': 12, 'Place': 'Home'},
{'Name': 'Bob', 'Time': 11, 'Place': 'Home'},
{'Name': 'Jerry', 'Time': 5, 'Place': 'Home'},
{'Name': 'Jerry', 'Time': 11, 'Place': '-----'},
{'Name': 'Jerry', 'Time': 11, 'Place': 'Work'}]

最终需要的数据:

[{"Name": "Bob", "Details":[{"Place":"Home", "Time":[12, 11]}]}, 
{"Name": "Jerry", "Details":[{"Place":"Home", "Time":[5]},
{"Place":"-----", "Time":[11]},
{"Place":"Work", "Time":[11]}]}]

最佳答案

您可以使用 itertools.groupbyNamePlace 分组,

>>> import itertools
>>> from collections import defaultdict
>>> data
[{'Name': 'Bob', 'Time': 12, 'Place': 'Home'}, {'Name': 'Bob', 'Time': 11, 'Place': 'Home'}, {'Name': 'Jerry', 'Time': 5, 'Place': 'Home'}, {'Name': 'Jerry', 'Time': 11, 'Place': '-----'}, {'Name': 'Jerry', 'Time': 11, 'Place': 'Work'}]
>>> sorted_data = sorted(data, key=lambda x: (x['Name'], x['Place'])) # sorting before grouping as suggested by @wwii, because The returned group is itself an iterator that shares the underlying iterable with groupby(). Please see (https://docs.python.org/3/library/itertools.html#itertools.groupby)
>>> d = defaultdict(list)
>>> y = itertools.groupby(sorted_data, lambda x: (x['Name'], x['Place']))
>>> for group, grouper in y:
... time_ = [item['Time'] for item in grouper]
... name, place = group
... d[name].append({'Place': place, 'Time': time_})
...
>>> d
defaultdict(<class 'list'>, {'Bob': [{'Place': 'Home', 'Time': [12, 11]}], 'Jerry': [{'Place': 'Home', 'Time': [5]}, {'Place': '-----', 'Time': [11]}, {'Place': 'Work', 'Time': [11]}]})
>>> pprint.pprint(dict(d))
{'Bob': [{'Place': 'Home', 'Time': [12, 11]}],
'Jerry': [{'Place': 'Home', 'Time': [5]},
{'Place': '-----', 'Time': [11]},
{'Place': 'Work', 'Time': [11]}]}

如果您需要当时显示的确切结构,

>>> f_data = []
>>> for key, value in d.items():
... f_data.append({'Name': key, 'Details': value})
...
>>> pprint.pprint(f_data)
[{'Details': [{'Place': 'Home', 'Time': [12, 11]}], 'Name': 'Bob'},
{'Details': [{'Place': '-----', 'Time': [11]},
{'Place': 'Home', 'Time': [5]},
{'Place': 'Work', 'Time': [11]}],
'Name': 'Jerry'}]

关于python - 嵌套的 defaultdict(list) 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55762857/

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