问题:
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(代币): 计数 = 0 对于 token 中的 token : 如果 token[0] == '<' 和 token[-1] == '>': 计数 += 1 返回计数 list1 = ['', 'Hello World!', ''] 计数 = tag_count(list1) print("预期结果:2,实际结果:{}".format(count))
我的结果总是0。我做错了什么?
请您参考如下方法:
首先,您没有计算任何东西,因为您正在重新定义 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(">"))
