xml - Python: Better solution to repeat function invocation in comprehension -
i have xml file which, need extract id , title fields (under page tag). doing, , works fine. but, not happy 3 calls elem.find('title). there better approach avoid comprehensions? understand writing in loop solve problem.
import xml.etree.elementtree et tree = et.parse(some file) root = tree.getroot() id_title_list = [(elem.find('id').text, elem.find('title').text) elem in root.findall('page') if elem.find('title').text.startswith('string1') or elem.find('title').text.startswith('string2')]
there nothing wrong in breaking down normal loop , having intermediate variables:
id_title_list = [] elem in root.findall('page'): title = elem.find('title').text if title.startswith(('string1', 'string2')): id_title_list.append((elem.find('id').text, title))
note startswith()
supports multiple prefixes passed in tuple.
another option make startswith()
checks inside xpath expression:
id_title_list = [(elem.find('id').text, elem.find('title').text) elem in root.xpath('//page[.//title[starts-with(., "string1") or starts-with(., "string2")])]']
note not work xml.etree.elementtree
since provides limited support xpath expressions. lxml
handle this, change import to:
from lxml import etree et
Comments
Post a Comment