標籤:參數 迴圈 `` Null 字元串 部分 count == 標準 lis
列表與迴圈問題
- 編寫一個函數 tag_count,其參數以字串列表的形式列出。該函數應該返回字串中有多少個 XML 標籤。XML 是類似於 HTML 的資料語言。你可以通過一個字串是否是以左角括弧 "<" 開始,以右角括弧 ">" 結尾來判斷該字串是否為 XML 標籤。
可以假設作為輸入的字串列表不包含Null 字元串。
"""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資料結構第一部分,列表與for迴圈