您的位置:首页 > 理论基础 > 数据结构算法

Python培训知识总结系列- 第二章Python数据结构第一部分,列表与for循环

2018-01-26 17:58 549 查看
列表与循环问题

编写一个函数 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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 培训知识
相关文章推荐