我有一个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')]
是三个电话的问题,或者这是一个情况下,[过早的优化(https://en.wikipedia.org/wiki/Program_optimization #When_to_optimize)(万恶之源)? – martineau 2014-09-10 18:15:43
而不是两次调用'startswith',使用元组'('string1','string2')'作为参数进行一次调用。 – chepner 2014-09-10 19:06:51