我下载了Google的Python练习,这是问题之一:
给定一个字符串列表,返回字符串长度为2或更大且字符串的第一个和最后一个字符相同的字符串数的计数
我对此的回答如下:
def match_ends(words):
a=[]
for word in words:
if len(word)>=2 and word[0]==word[-1]:
a=a.append(word)
return len(a)
Run Code Online (Sandbox Code Playgroud)
但是,对于此列表:
words=['aba', 'xyz', 'aa', 'x', 'bbb']
Run Code Online (Sandbox Code Playgroud)
它只返回“ 1”。我不明白,为什么append在转弯时不添加所有与之匹配的字符串。
这是Google的解决方案:
def match_ends(words):
count = 0
for word in words:
if len(word) >= 2 and word[0] == word[-1]:
count = count + 1
return count
Run Code Online (Sandbox Code Playgroud)