【问题标题】:Create a list of sublist while itiretating through XML file遍历 XML 文件时创建子列表列表
【发布时间】:2021-01-27 17:25:59
【问题描述】:

我的问题如下:我不知道如何使用 lxml 库从 xml 文件创建不同变量的字典。

这是 xml 文件的示例:

  <Patterns>
    <Pattern ID="0" weight="1">
      <PatternEntries>
        <PatternEntry index="0">
          <ShiftType>L</ShiftType>
        </PatternEntry>
        <PatternEntry index="1">
          <ShiftType>D</ShiftType>
        </PatternEntry>
      </PatternEntries>
    </Pattern>
    <Pattern ID="1" weight="1">
      <PatternEntries>
        <PatternEntry index="0">
          <ShiftType>D</ShiftType>
        </PatternEntry>
        <PatternEntry index="1">
          <ShiftType>E</ShiftType>
        </PatternEntry>
      </PatternEntries>
    </Pattern>

我想要创建一个字典,其中模式 ID 作为键,班次类型和日期作为值,如下所示:{Pattern ID :[ShiftType]}。问题来自班次列表。所以我在想它创建一个子列表,其中每个 ID 的每个元素都存储在一个子列表中,所有 ID 的所有元素都存储在一个通用列表中。谢谢 !这是我的代码

for ID in root.xpath('//Patterns'):
    pattern_ID = ID.xpath('./Pattern/@ID')
    for shift in root.xpath('.//PatternEntries/PatternEntry/ShiftType'):
        shift_list.append(shift.text)

预期输出:

{0:[L,D], 1:[D,E]}

【问题讨论】:

  • 您可以编辑您的问题并显示确切的预期输出吗?

标签: python xml list parsing lxml


【解决方案1】:

你可能需要这些方面的东西:

from lxml import etree
patterns = """[your xml above, fixed - it's missing the closing </Patterns>]"""

doc = etree.fromstring(patterns)
p_dict = {}
pat = doc.xpath('//Pattern')
for p in pat:
    key = p.xpath('./@ID')[0]
    vals = p.xpath('.//ShiftType/text()')
    p_dict[key]=vals
p_dict

输出:

{'0': ['L', 'D'], '1': ['D', 'E']}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 2021-12-24
    • 2020-07-18
    相关资源
    最近更新 更多