1
taogen 2021-01-16 23:21:31 +08:00 via Android
没写过 Python 。不过把对象数组变成哈希数组,不会很难吧
|
2
yixiugegegege OP @taogen 我百度一手,谢谢
|
3
nvkou 2021-01-16 23:28:36 +08:00 via Android
Java 的话第一反应是 stream. map. groupingby
Python 的话我估计也会这么做 大不了先拿 firstletter 的集合,再用这个集合过滤到不同组。也就是先建立键,再通过键过滤值 |
4
eggshell 2021-01-16 23:34:55 +08:00
用 itertools.groupby
|
5
xiaoming1992 2021-01-16 23:40:46 +08:00 via Android
就用 for in 也行吧
|
6
wzwwzw 2021-01-16 23:43:55 +08:00
from itertools import groupby
before_data = { "child": [ {"f_brandname": "奔驰", "f_pyfirstletter": "B", "seriesname": "载货车"}, {"f_brandname": "北奔重卡", "f_pyfirstletter": "B", "seriesname": "载货车"}, {"f_brandname": "福田欧曼", "f_pyfirstletter": "F", "seriesname": "载货车"}, {"f_brandname": "江铃汽车", "f_pyfirstletter": "J", "seriesname": "载货车"}, ] } after_data = {"child": {}} for j, i in groupby(before_data["child"], key=lambda x: x["f_pyfirstletter"]): if j not in after_data["child"]: after_data_example["child"][j] = [] for k in i: after_data_example["child"][j].append(k) print(after_data_example) |
7
zyx199199 2021-01-16 23:46:16 +08:00 2
···
from itertools import groupby {k: list(v) for k,v in groupby(data['child'], key=lambda x: x["f_pyfirstletter"])} ``` |
8
yixiugegegege OP @eggshell 卧槽,解决了,老哥,谢谢!!!
|
9
my8100 2021-01-16 23:46:43 +08:00 via iPhone
from collections import defaultdict
child_dict = defaultdict(list) for d in data["child"]: child_dict[d["f_pyfirstletter"]].append(d) assert {"child": child_dict} == target_data |
10
yixiugegegege OP @wzwwzw 谢谢老哥的代码,终于解决了哭😭
|
11
yixiugegegege OP @zyx199199 谢谢老哥解决了,喜极而泣,祝福本月无 bug,无迫于
|
12
yixiugegegege OP @my8100 谢谢老哥,❤️你,爱你😭!
|
13
imn1 2021-01-16 23:58:51 +08:00
new = {'child': {x["f_pyfirstletter"]: [] for x in d["child"]}}
[new['child'][x["f_pyfirstletter"]].append(x) for x in d["child"]] 下划线为空格 d 为源字典,new 为结果 |
14
imn1 2021-01-17 00:05:15 +08:00
# 13 “下划线为空格”不需要
原来是用 for 的,有缩进,后来改成列表表达式,不需要缩进了 |