简体   繁体   中英

How can I count XML string elements in a python list?

The problem:

Write a function, tag_count , that takes as its argument a list of strings. It should return a count of how many of those strings are XML tags. You can tell if a string is an XML tag if it begins with a left angle bracket "<" and end with a right angle bracket ">".

def tag_count(tokens): count = 0 for token in tokens: if token[0] == '<' and token[-1] == '>': count += 1 return count list1 = ['', 'Hello World!', ''] count = tag_count(list1) print("Expected result: 2, Actual result: {}".format(count))

My results are always 0 . What am I doing wrong?

First of all, you are not counting anything since you are redefining count variable in the loop. Also, you are actually missing the XML string check (starts with < and ends with > ).

Fixed version:

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

Which you may then improve by using the built-in sum() function:

def tag_count(list_strings):
    return sum(1 for item in list_strings
               if item.startswith("<") and item.endswith(">"))
    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'.
for count, xml_list in enumerate(xml_list)
    if str(xml_list).startwith("<") and str(xml_list).endswith(">")
       print(count)

#xml tag list counter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM