你在做什么在你的函数遍历所有对你碰巧在你的XML元素。一旦你完成了迭代,你将返回任何值c1和c2最终被赋值(这可能不是来自同一个孩子,就像你写的代码的方式),它们可能是最后一对元素或者c1和c2对应的到它们在xml中的最后一次出现(因为您没有对之前获得的值对进行任何操作)。
你这里有两种方法:
1)建立一个结构,例如元组的列表,或者更好的是,字典和不断增加的(C1,C2)的元素有:
def getLetters(data):
result = []
for child in data:
# use other default values here if more suitable
c1 = None
c2 = None
if child.attrib['c1']:
c1 = child.attrib['c1']
if child.attrib['c2']:
c2 = child.attrib['c2']
result.append({'c1':c1, 'c2':c2}) # append your next entry as a mini-dictionary
return result
for entry in getLetters(data):
print 'c1', entry['c1'], 'c2', entry['c2']
2)使用收益,这可能是处理大块数据的更有效的方式,因为你在进一步传递之前,不必等待所有处理完成。
def getLetters(data):
for child in data:
# use other default values here if more suitable
c1 = None
c2 = None
if child.attrib['c1']:
c1 = child.attrib['c1']
if child.attrib['c2']:
c2 = child.attrib['c2']
yield {'c1':c1, 'c2':c2} # yield the mini-dictionary for every child
# no return needed here
# you can process the output in the same way:
for entry in getLetters(data):
print 'c1', entry['c1'], 'c2', entry['c2']
您只能'return'一次,在这种情况下你'for'循环结束。 – jonrsharpe
谢谢,我不应该在这种情况下使用构造函数?我应该使用什么? – user2598997
@ user2598997我在代码中看不到构造函数。 – timgeb