请参阅附件。我刚接触python (以及一般的编程;转行;tldr:我是个新手)。
我不知道我可以编写什么函数来返回列表中xml标记的数量。请帮帮忙。

发布于 2017-12-17 01:25:12
正如问题所述:
如果字符串以<开头并以>结尾,则可以检查该字符串是否为
标记
您需要遍历列表中的每个字符串,并使用str.startswith()和str.endswith()检查第一个和最后一个字符:
In [1]: l = ["<string1>", "somethingelse", "</string1>"]
In [2]: [item for item in l if item.startswith("<") and item.endswith(">")]
Out[2]: ['<string1>', '</string1>']在这里,我们只过滤了list comprehension中所需的字符串,但是为了计算我们得到的匹配项的数量,我们可以使用sum()在每次有匹配项时添加一个1:
In [3]: sum(1 for item in l if item.startswith("<") and item.endswith(">"))
Out[3]: 2虽然这只是一种方法,但我不确定你在课程中走了多远。一个更天真、更直接的答案可能是:
def tag_count(l):
count = 0
for item in l:
if item.startswith("<") and item.endswith(">"):
count += 1
return count发布于 2019-12-17 08:19:55
tokens = ['<greeting>', 'Hello World!', '</greeting>']
count = 0
# write your for loop here
for token in tokens:
if token.startswith("<") and token.endswith(">"):
count += 1
print(count)https://stackoverflow.com/questions/47848199
复制相似问题