私信  •  关注

Michael H.

Michael H. 最近创建的主题
Michael H. 最近回复了
5 年前
回复了 Michael H. 创建的主题 » 将Python字典中的JSON值累积为数组
data = { 
    "links": [
        {"source":"0","target":"1","weight":1,"color":"white"},
        {"source":"0","target":"2","weight":1,"color":"yellow"},
        {"source":"0","target":"3","weight":1,"color":"white"},
        {"source":"5","target":"7","weight":1,"color":"white"},
        {"source":"5","target":"8","weight":1,"color":"yellow"},
        {"source":"6","target":"9","weight":1,"color":"white"},
    ]
}

collected = []
for obj in data["links"]:
    source_matches = [item for item in collected if item["source"] == obj["source"]]
    if len(source_matches) == 0:
        source_match = {"source": obj["source"], "neighbour": [obj["target"]]}
        collected.append(source_match)
    elif len(source_matches) == 1:
        source_matches[0]["neighbour"].append(obj["target"])
    else:
        raise BaseException()

print(collected)  # [{'source': '0', 'neighbour': ['1', '2', '3']}, {'source': '5', 'neighbour': ['7', '8']}, {'source': '6', 'neighbour': ['9']}]

不是很优雅,但能胜任工作。

如果你真的不需要格式 {"source": 0, "neighbors": ["1","2","3"]} 我建议使用上面的解决方案 defaultdict . 如果需要这种格式,还可以从 默认听写 解决方案。