Python培训知识总结系列- 第二章Python数据结构第一部分,列表与for循环
2018-01-26 17:58
549 查看
列表与循环问题
编写一个函数 tag_count,其参数以字符串列表的形式列出。该函数应该返回字符串中有多少个 XML 标签。XML 是类似于 HTML 的数据语言。你可以通过一个字符串是否是以左尖括号 "<" 开始,以右尖括号 ">" 结尾来判断该字符串是否为 XML 标签。
可以假设作为输入的字符串列表不包含空字符串。
"""Write a function,
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
编写一个函数 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培训知识总结系列- 第二章Python数据结构第二部分,字符串拼接
- Python培训知识总结系列- 第二章Python数据结构第三部分-字典,集合
- Python培训知识总结系列- 第二章Python数据结构第四部分-字典操作
- Python培训知识总结系列- 第三章 Python3文件操作(一)
- Python培训知识总结系列- 第一章Python编程基础
- Python数据结构:序列(列表[]、元组())与映射(字典{})语法总结
- Python数据结构:序列(列表[]、元组())与映射(字典{})语法总结
- Python数据结构:序列(列表[]、元组())与映射(字典{})语法总结
- 《数据结构》第二章知识总结导图
- 《数据结构》第二章 线性表 知识总结导图
- Python数据结构:序列(列表[]、元组())与映射(字典{})语法总结
- Python数据结构:序列(列表[]、元组())与映射(字典{})语法总结
- 史上最全的Python数据结构:列表和元组用法总结
- Python数据结构:序列(列表[]、元组())与映射(字典{})语法总结
- Python数据结构:序列(列表[]、元组())与映射(字典{})语法总结
- Python数据结构:序列(列表[]、元组())与映射(字典{})语法总结
- Python数据结构中列表,字典,元组,集合的总结
- python基础系列教程——数据结构(列表、元组、字典、集合、链表)
- Python数据结构:序列(列表[]、元组())与映射(字典{})语法总结
- python基础知识——内置数据结构(列表)