列表理解和len()与简单的for循环

问题描述:

我应该列出一个单词列表,并对其中所有长度大于或等于2个字符且第一个和最后一个字符相等的所有单词进行计数.

I'm supposed to take a list of words and count all words in it which are 2 or more characters long and where the first and last character are equal.

我想出了两种可能的解决方案:

I came up with two possible solutions:

result = 0
for word in words:
    if len(word) >= 2 and word[0] == word[-1]:
        result += 1
return result

vs.

return len([word for word in words if len(word) >= 2 and word[0] == word[-1]])

哪个是首选解决方案?还是有更好的呢?

Which one would be the preferred solution? Or are there even better ones?

在第二个示例中,

In your second example a generator expression would be better than list-comp if your list is large.

sum(1 for word in words if len(word) >= 2 and word[0] == word[-1])