迫于逻辑实在理不清了, Python 求助

2021-01-16 23:11:19 +08:00
 yixiugegegege
{
"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": "载货车"
}]
}

变成

{
"child": {
"B": [{
"f_brandname": "奔驰",
"f_pyfirstletter": "B",
"seriesname": "载货车"
}, {
"f_brandname": "北奔重卡",
"f_pyfirstletter": "B",
"seriesname": "载货车"
}],
"F": [{
"f_brandname": "福田欧曼",
"f_pyfirstletter": "F",
"seriesname": "载货车"
}],
"J": [{
"f_brandname": "江铃汽车",
"f_pyfirstletter": "J",
"seriesname": "载货车"
}]
}
}


就是把每个小字典给归类了,还有好多个品牌,这个是少数
语言是 python,求 demo,
2887 次点击
所在节点    Python
14 条回复
taogen
2021-01-16 23:21:31 +08:00
没写过 Python 。不过把对象数组变成哈希数组,不会很难吧
yixiugegegege
2021-01-16 23:27:52 +08:00
@taogen 我百度一手,谢谢
nvkou
2021-01-16 23:28:36 +08:00
Java 的话第一反应是 stream. map. groupingby
Python 的话我估计也会这么做
大不了先拿 firstletter 的集合,再用这个集合过滤到不同组。也就是先建立键,再通过键过滤值
eggshell
2021-01-16 23:34:55 +08:00
用 itertools.groupby
xiaoming1992
2021-01-16 23:40:46 +08:00
就用 for in 也行吧
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)
zyx199199
2021-01-16 23:46:16 +08:00
···
from itertools import groupby

{k: list(v) for k,v in groupby(data['child'], key=lambda x: x["f_pyfirstletter"])}
```
yixiugegegege
2021-01-16 23:46:28 +08:00
@eggshell 卧槽,解决了,老哥,谢谢!!!
my8100
2021-01-16 23:46:43 +08:00
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
yixiugegegege
2021-01-16 23:46:55 +08:00
@wzwwzw 谢谢老哥的代码,终于解决了哭😭
yixiugegegege
2021-01-16 23:48:18 +08:00
@zyx199199 谢谢老哥解决了,喜极而泣,祝福本月无 bug,无迫于
yixiugegegege
2021-01-16 23:49:05 +08:00
@my8100 谢谢老哥,❤️你,爱你😭!
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 为结果
imn1
2021-01-17 00:05:15 +08:00
# 13 “下划线为空格”不需要
原来是用 for 的,有缩进,后来改成列表表达式,不需要缩进了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/745559

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX