Python - ETree element.find 部分匹配

Python - ETree element.find on a partial match

下面的代码片段循环遍历几个 xml 文件,并从每个文件中提取 3 "columns" 个字典。其中一个 xml 的第一个字段名称略有不同 "IndexName" 而不是 "IndexID"。我该怎么做才能摆脱单个字段列表,例如

field_list = ['Index*', 'CompositeSpread', 'CompositePrice',]

找到部分匹配:

strXpath = "./row"

field_list = ['IndexID', 'CompositeSpread', 'CompositePrice',]
field_list1 = ['IndexName', 'CompositeSpread', 'CompositePrice',]

tree = ET.parse(file_path)
root = tree.getroot()

value_list = []
for el in root.findall(strXpath):
    value_list.append([el.find(x).text for x in field_list])

我想出的解决方案是同时使用 field_list 中的 'IndexID''IndexName' 字段,并检查列表理解中的 if el.find(x) is not None

import xml.etree.ElementTree as ET

    strXpath = "./row"

    field_list = ['IndexName', 'IndexID', 'CompositeSpread', 'CompositePrice',]

    tree = ET.parse(file_path)
    root = tree.getroot()

    value_list = []
    for el in root.findall(strXpath):
        value_list.append([el.find(x).text for x in field_list if el.find(x) is not None])