2015-12-29 90 views
0

为什么此示例仅返回最后一个子属性,我如何获取它们全部?构造函数中的迭代返回

输入:

<root c1="A" c2="B"</root> 
    <root c1="A" c2="C"</root> 

脚本:

data = ElementTree.parse("./test.xml").getroot() 
    def getLetters(data): 
     for child in data: 
      if child.attrib['c1']: 
       c1 = child.attrib['c1'] 
      if child.attrib['c2']: 
       c2 = child.attrib['c2'] 
     return c1, c2 
    print getLetters(data) 

结果总是覆盖,我得到的最后一个孩子。

我已经试过产量,但仍然有同样的问题:

 yield c1, c2 
    generator = getLetters(data) 
    for i in generator: 
     print i 
+2

您只能'return'一次,在这种情况下你'for'循环结束。 – jonrsharpe

+0

谢谢,我不应该在这种情况下使用构造函数?我应该使用什么? – user2598997

+0

@ user2598997我在代码中看不到构造函数。 – timgeb

回答

1

你在做什么在你的函数遍历所有对你碰巧在你的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'] 
0
class getLetters: 
      def __init__(self): 
       self.c1 = child.attrib['c1'] 
       self.c2 = child.attrib['c2'] 

    for child in data: 
     i = getLetters() 
     c1 = i.c1 
     c2 = i.c2 
     print c1, c2