使用Python 3.x从XML子节点值创建唯一值列表

时间:2017-03-26 21:38:53

标签: xml python-3.x

我正在尝试创建一个唯一的GRADE值列表(在下面的示例中,结果集将是:GR12,GR10,GR9,GR11):

<School>
<SchoolNumber>123456</SchoolNumber>
<Students>
    <Student>
        <ID>1</ID><Grade>GR12</Grade><Name>A. Green</Name>
    </Student>
    <Student>
        <ID>2</ID><Grade>GR9</Grade><Name>B. Green</Name>
    </Student>
    <Student>
        <ID>1</ID><Grade>GR12</Grade><Name>A. Blue</Name>
    </Student>
    <Student>
        <ID>2</ID><Grade>GR9</Grade><Name>B. Blue</Name>
    </Student>
    <Student>
        <ID>3</ID><Grade>GR11</Grade><Name>C. Blue</Name>
    </Student>
    <Student>
        <ID>1</ID><Grade>GR9</Grade><Name>A. Redd</Name>
    </Student>
    <Student>
        <ID>2</ID><Grade>GR9</Grade><Name>B. Redd</Name>
    </Student>
    <Student>
        <ID>3</ID><Grade>GR10</Grade><Name>C. Redd</Name>
    </Student>
</Students>

我使用XML ElementTree生成所有GRADE值的列表,然后尝试使用set()创建唯一列表,如下所示:

grades = root.findall('.//{http://anysite.com}Grade')
unique_grades = list(set(grades))

但是,unique_grades []列表包含与grade []列表相同数量的元素。我一直在阅读https://docs.python.org/3.6/library/xml.etree.elementtree.html 文档(我对Python完全不熟悉并在学习的过程中学习),但我无法解决这个问题。任何建议/帮助将非常感谢。问候,戴夫。

1 个答案:

答案 0 :(得分:3)

你应该使用元素的内部文本而不是元素本身来调用set。前者将进行字符串比较,而后者将通过引用比较Element个对象,这不会改变输出中元素的数量,因为输入已经是一组不同的对象:

grades = root.findall('.//{http://anysite.com}Grade')
unique_grades = list(set(g.text for g in grades))