我应该取一个单词列表并计算其中长度为2个或更多字符且第一个和最后一个字符相等的所有单词.
我想出了两个可能的解决方案:
result = 0
for word in words:
if len(word) >= 2 and word[0] == word[-1]:
result += 1
return result
Run Code Online (Sandbox Code Playgroud)
与
return len([word for word in words if len(word) >= 2 and word[0] == word[-1]])
Run Code Online (Sandbox Code Playgroud)
哪一个是首选解决方案?还是有更好的?