2014-09-10 59 views
1

我有一个XML文件,我需要从中提取ID和标题字段(在页面标签下)。这就是我正在做的,它工作正常。但是,对于elem.find('title)的三次调用我不满意。有没有更好的方法来避免理解?我明白,写在一个循环将解决这个问题。Python:理解中重复函数调用的更好的解决方案

import xml.etree.ElementTree as ET 
tree = ET.parse(some file) 
root = tree.getroot() 
id_title_list = [(elem.find('id').text, elem.find('title').text) 
        for elem in root.findall('page') 
        if elem.find('title').text.startswith('string1') or 
        elem.find('title').text.startswith('string2')] 
+0

是三个电话的问题,或者这是一个情况下,[过早的优化(https://en.wikipedia.org/wiki/Program_optimization #When_to_optimize)(万恶之源)? – martineau 2014-09-10 18:15:43

+0

而不是两次调用'startswith',使用元组'('string1','string2')'作为参数进行一次调用。 – chepner 2014-09-10 19:06:51

回答

4

没有什么错在它分解到一个正常的循环,并具有中间变量:

id_title_list = [] 
for elem in root.findall('page'): 
    title = elem.find('title').text 
    if title.startswith(('string1', 'string2')): 
     id_title_list.append((elem.find('id').text, title)) 

注意startswith()支持传过来的元组多个前缀。


另一种选择将是使XPath表达式内startswith()检查:

id_title_list = [(elem.find('id').text, elem.find('title').text) 
        for elem in root.xpath('//page[.//title[starts-with(., "string1") or starts-with(., "string2")])]'] 

注意,因为它提供了XPath表达式只提供有限的支持,这将不会xml.etree.ElementTree工作。 lxml会处理这个问题,只是改变了进口:

from lxml import etree as ET 
+3

是的。不要在不需要时滥用列表解析。没有人欣赏简单的循环了。 – 2014-09-10 18:33:58

1

的一种方式,尊重的要求,这与理解来解决:

id_title_list = [ 
    (elem.find('id').text, title) 
     for elem, title in 
      (elem, elem.find('title').text for elem in root.findall('page')) 
       if title.startswith(('string1', 'string2'))] 

它使用一个内部产生表达的唯一find评价每个元素一次。因为它是一个懒惰评估的生成器,它应该避免中间列表的开销。它也使用startswith的能力来获取可能的前缀元组,尽管一次只查找标题文本,而不是速度的简洁性。

所有这一切说,我同意亚历克斯的答案,for循环是一个更好的选择。

0

对于某些高阶函数和itertools:

from operator import methodcaller 
from itertools import tee, imap, izip 

# Broken down into lots of small pieces; recombine as you see fit. 

# Functions for calling various methods on objects 
# Example: find_id(x) is the same as x.find('id') 
find_id = methodcaller('find', 'id') 
find_title = methodcaller('find', 'title') 
is_valid = methodcaller('startswith', ('string1', 'string2')) 
get_text = attrgetter('text') 

found = root.findall('page') # The original results... 
found_iters = tee(found, 2) # ... split into two. 

# Make two iterators resulting from calling `find` on each element... 
ids_iter = imap(get_text, imap(find_id, found_iters[0])) 
titles_iter = imap(get_text, imap(find_title, found_iters[1])) 

# And recombine them into a single iterable of tuples. 
id_title_pairs = izip(ids_iter, titles_iter) 

# Resulting in a nice, simple list comprehension 
id_title_list = [(id, title) 
        for id, title in id_title_pairs if is_valid(title)]