2017-07-29 111 views
1

問題:如何計算python列表中的XML字符串元素?

寫一個函數,tag_count,即作爲其參數 字符串列表。它應該返回這些字符串中有多少是XML 標籤的計數。如果一個字符串是一個XML標記,如果它以左邊的 角括號「<」開頭並以右尖括號「>」結尾,則可以判斷它是否爲XML標記。

def tag_count(list_strings): 
    count = 0 
    xml = '<' 
    for xml in list_strings: 
     count += count 
    return count 
list1 = ['<greeting>', 'Hello World!', '</greeting>'] 
count = tag_count(list1) 
print("Expected result: 2, Actual result: {}".format(count)) 

我的結果總是0。我究竟做錯了什麼?

回答

2

首先,由於您在循環中重新定義了count變量,因此您不計算任何內容。此外,您實際上錯過了XML字符串檢查(從<開始,並以>結束)。

修正版本:

def tag_count(list_strings): 
    count = 0 
    for item in list_strings: 
     if item.startswith("<") and item.endswith(">"): 
      count += 1 
    return count 

,你可以再使用提高了內置sum()功能:

def tag_count(list_strings): 
    return sum(1 for item in list_strings 
       if item.startswith("<") and item.endswith(">")) 
+0

了相同的答案只是想後,但你早日公佈。 – bigbounty

0
def tag_count(xml_count): 
     count = 0 
     for xml in xml_count: 
      if xml[0] == '<' and xml[-1] == '>': 
       count += 1 
     return count 


# This is by using positional arguments 
# in python. You first check the zeroth 
# element, if it's a '<' and then the last 
# element, if it's a '>'. If True, then increment 
# variable 'count'. 
相關問題