列表理解和len()与简单的for循环 [英] List comprehension and len() vs. simple for loop

查看:377
本文介绍了列表理解和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])

这篇关于列表理解和len()与简单的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆