计算列表中每个元素的长度

huangapple go评论72阅读模式
英文:

Counting the length of each element inside a list

问题

我的任务是仅打印长度小于4个字符的单词。我已尝试了无数种方法,但总是出现错误。非常感谢任何帮助。

b = find_short_words(['dog', 'cat', 'turtle', 'horse', 'pangolin'])

short_words = [word for word in b if len(word) < 4]

尝试使用len函数的循环,但总是返回错误。

英文:

My task is to print only the words that are shorter than 4 characters. I have tried it countless ways, but there is always an error. Would very much appreciate any help.


b = find_short_words([&#39;dog&#39;, &#39;cat&#39;, &#39;turtle&#39;, &#39;horse&#39;, &#39;pangolin&#39;])

short_words = [word for word in b if len(name)]&lt;5

Tried loops with len function, but it always returns an error.

答案1

得分: 2

您正在将一个列表与一个整数进行比较,这是无效的。

words = ['dog', 'cat', 'turtle', 'horse', 'pangolin']
short_words = [word for word in words if len(word) < 5] # 将<5放入循环内
print(short_words)
英文:

You are comparing a list with a integer, which is invalid.

words = [&#39;dog&#39;, &#39;cat&#39;, &#39;turtle&#39;, &#39;horse&#39;, &#39;pangolin&#39;]
short_words = [word for word in words if len(word) &lt; 5] # put &lt;5 inside loop
print(short_words)

huangapple
  • 本文由 发表于 2023年6月12日 09:04:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定