面对一个可迭代对象,如何进行选定呢?
如果不想记,这个可迭代对象的专用语法,有两种通用方法:

方法一:list(可迭代对象)转化为列表

这个使用print(list(可迭代对象)[index])访问特定的对象
适用范围:可迭代对象的数据量不大,内存可以容纳下
举个例子:

  1. # 需求:把下面content里根标签下第二个country节点 的属性打印出来
  2. content = """
  3. <data>
  4. <country name="Liechtenstein">
  5. <rank>2</rank>
  6. <year>2023</year>
  7. <gdppc>141100</gdppc>
  8. <neighbor direction="E" name="Austria" />
  9. <neighbor direction="W" name="Switzerland" />
  10. </country>
  11. <country name="Panama">
  12. <rank>69</rank>
  13. <year>2026</year>
  14. <gdppc>13600</gdppc>
  15. <neighbor direction="W" name="Costa Rica" />
  16. <neighbor direction="E" name="Colombia" />
  17. </country>
  18. </data>
  19. """

原本的方法是使用findall变成列表,现在只需要直接list

  1. from xml.etree import ElementTree as ET
  2. content = """
  3. <data>
  4. <country name="Liechtenstein">
  5. <rank>2</rank>
  6. <year>2023</year>
  7. <gdppc>141100</gdppc>
  8. <neighbor direction="E" name="Austria" />
  9. <neighbor direction="W" name="Switzerland" />
  10. </country>
  11. <country name="Panama">
  12. <rank>69</rank>
  13. <year>2026</year>
  14. <gdppc>13600</gdppc>
  15. <neighbor direction="W" name="Costa Rica" />
  16. <neighbor direction="E" name="Colombia" />
  17. </country>
  18. </data>
  19. """
  20. root = ET.XML(content)
  21. # 原先的办法
  22. print(root.findall('country')[1].attrib)
  23. # 使用list通法
  24. print(list(root)[1].attrib)

方法二:使用iter转化为生成器进行迭代

  1. from xml.etree import ElementTree as ET
  2. content = """
  3. <data>
  4. <country name="Liechtenstein">
  5. <rank>2</rank>
  6. <year>2023</year>
  7. <gdppc>141100</gdppc>
  8. <neighbor direction="E" name="Austria" />
  9. <neighbor direction="W" name="Switzerland" />
  10. </country>
  11. <country name="Panama">
  12. <rank>69</rank>
  13. <year>2026</year>
  14. <gdppc>13600</gdppc>
  15. <neighbor direction="W" name="Costa Rica" />
  16. <neighbor direction="E" name="Colombia" />
  17. </country>
  18. </data>
  19. """
  20. root = ET.XML(content)
  21. # 由于root是个可迭代对象,所以先转化为生成器
  22. root_gen = iter(root)
  23. # 由于我们要访问第二个country,所以循环两次
  24. for count in range(2):
  25. sub_root = next(root_gen)
  26. # 输出第二个country的属性
  27. print(sub_root.attrib)