列表与循环问题
- 编写一个函数 tag_count,其参数以字符串列表的形式列出。该函数应该返回字符串中有多少个 XML 标签。XML 是类似于 HTML 的数据语言。你可以通过一个字符串是否是以左尖括号 "<" 开始,以右尖括号 ">" 结尾来判断该字符串是否为 XML 标签。
可以假设作为输入的字符串列表不包含空字符串。
"""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 ends with a right angle bracket ">".
"""
#TODO: Define the tag_count function
def tag_count(list):
count=0
for each in list:
a=",".join(each.title())
print(a)
if a[0]==‘<‘ and a[-1]==‘>‘:
count=count+1
return count
list1 = [‘<greeting>‘, ‘Hello World!‘, ‘</greeting>‘]
count = tag_count(list1)
print("Expected result: 2, Actual result: {}".format(count))
我是把列表转成字符串,字符串以“,”分割,然后判断是否是第一个与最后一个是<,>
标准答案: ```python
def tag_count(tokens):
count = 0
for token in tokens:
if token[0] == ‘<‘ and token[-1] == ‘>‘:
count += 1
return count
I use string indexing to find out if each token begins and ends with angle brackets.
原文地址:http://blog.51cto.com/huangsheng2/2065574