以下算法的更Pythonic方法

2024-04-20 11:49:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我用更合乎逻辑的方法改变了最后的结构:

{'state1': {'city1': ['dict1', 'dict2']}, 'state2': {'City2': ['dict3']}}

代码是:

dir_dict = {}
for one in objects:
    state = one.dir.city.state.name
    city ​​= one.dir.city.name
    address = one.dir.address
    if state not in dir_dict:
        dir_dict[state] = {}
    if city not in dir_dict[state]:
        dir_dict[state][city] = []
    dir_dict[state][city].append(address)

我仍然实现代码@Eric


Tags: 方法代码nameincityifaddressdir