Python培訓知識總結系列- 第二章Python資料結構第一部分,列表與for迴圈

來源:互聯網
上載者:User

標籤:參數   迴圈   ``   Null 字元串   部分   count   ==   標準   lis   

列表與迴圈問題

  1. 編寫一個函數 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迴圈

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.