hel*_*hod 6 python list-comprehension
我应该取一个单词列表并计算其中长度为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)
哪一个是首选解决方案?还是有更好的?
ber*_*nie 15
在第二个示例中,如果列表很大,则生成器表达式将优于list-comp.
sum(1 for word in words if len(word) >= 2 and word[0] == word[-1])
Run Code Online (Sandbox Code Playgroud)