【问题标题】:How can I count XML string elements in a python list?如何计算 python 列表中的 XML 字符串元素?
【发布时间】:2018-01-05 04:32:10
【问题描述】:

问题:

编写一个函数tag_count,它的参数是一个列表 字符串。它应该返回这些字符串中有多少是 XML 的计数 标签。如果字符串以 left 开头,您可以判断它是否是 XML 标记 尖括号“”结尾。

def tag_count(tokens): 计数 = 0 对于令牌中的令牌: 如果令牌 [0] == '': 计数 += 1 返回计数 list1 = ['', 'Hello World!', ''] 计数 = tag_count(list1) print("预期结果:2,实际结果:{}".format(count))

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:
        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'.
    

    【讨论】:

      【解决方案2】:

      首先,您没有计算任何内容,因为您在循环中重新定义了count 变量。此外,您实际上缺少 XML 字符串检查(以 &lt; 开头并以 &gt; 结尾)。

      固定版本:

      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(">"))
      

      【讨论】:

      • 同样的答案只是想发,但你发的早。
      猜你喜欢
      • 2020-10-23
      • 2022-08-13
      • 2016-01-03
      • 2023-02-25
      • 2020-01-28
      • 2019-09-05
      • 2017-02-25
      • 1970-01-01
      相关资源
      最近更新 更多