2017-07-29 113 views
1

问题:如何计算python列表中的XML字符串元素?

写一个函数,tag_count,即作为其参数 字符串列表。它应该返回这些字符串中有多少是XML 标签的计数。如果一个字符串是一个XML标记,如果它以左边的 角括号“<”开头并以右尖括号“>”结尾,则可以判断它是否为XML标记。

def tag_count(list_strings): 
    count = 0 
    xml = '<' 
    for xml in list_strings: 
     count += count 
    return count 
list1 = ['<greeting>', 'Hello World!', '</greeting>'] 
count = tag_count(list1) 
print("Expected result: 2, Actual result: {}".format(count)) 

我的结果总是0。我究竟做错了什么?

回答

2

首先,由于您在循环中重新定义了count变量,因此您不计算任何内容。此外,您实际上错过了XML字符串检查(从<开始,并以>结束)。

修正版本:

def tag_count(list_strings): 
    count = 0 
    for item in list_strings: 
     if item.startswith("<") and item.endswith(">"): 
      count += 1 
    return count 

,你可以再使用提高了内置sum()功能:

def tag_count(list_strings): 
    return sum(1 for item in list_strings 
       if item.startswith("<") and item.endswith(">")) 
+0

了相同的答案只是想后,但你早日公布。 – bigbounty

0
def tag_count(xml_count): 
     count = 0 
     for xml in xml_count: 
      if xml[0] == '<' and xml[-1] == '>': 
       count += 1 
     return count 


# This is by using positional arguments 
# in python. You first check the zeroth 
# element, if it's a '<' and then the last 
# element, if it's a '>'. If True, then increment 
# variable 'count'. 
相关问题