为什么循环中的函数结果不正确?

时间:2019-05-11 09:30:23

标签: python python-3.x jupyter-notebook

我尝试将XML中的某些数据放入模型对象中。 (XML的库-xml.etree.cElementTree) 我创建了函数“ split_path”,并尝试在循环中使用它。

#My function:
def split_path(diction):
    separated_path = output['path'].replace('$', '').split('/')
    for k in separated_path:
        path_dict = {'key':separated_path[0], 'table':separated_path[1], 'attribute':separated_path[2]}
    return path_dict

结果是我在木星笔记本上得到了

{'path': '$_source1/LDS_PERSONALDATEN_F/LDS_HID_PERSONEN_NR'}
{'key': '_target2', 'table': 'IDS_S_NAT_PERSON', 'attribute': 'IDS_H_NAT_PERSON_HID'}
{'path': '$_source698/LDS_PER/LDS_ONEN_NR'}
{'key': '_target2', 'table': 'IDS_S_NAT_PERSON', 'attribute': 'IDS_H_NAT_PERSON_HID'}

第一行和第三行表明我的论点正在改变。我不知道为什么第二和第四相同...

返回以上结果的部分代码:

# Code for checking result:
while mkey == 'input':
    print(m.attrib)
    print(split_path(m.attrib))
    break

1 个答案:

答案 0 :(得分:0)

def split_path(diction):
    separated_path = diction['path'].replace('$', '').split('/')
    for k in separated_path:
        path_dict = {'key':separated_path[0], 'table':separated_path[1], 'attribute':separated_path[2]}
    return path_dict

您使用了错误的变量名-输出而不是命令

在遍历separated_path时,您将覆盖path_dict。因此,您的结果将只是最后一次迭代的结果。那真的是你想要的吗?