python返回具有一定长度的列表元素 [英] python- return elements of list that have certain length
本文介绍了python返回具有一定长度的列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
字是一个列表,大小在这里是一个正整数。
结果应该是这样的。
by_size(['a','bb','ccc', 'dd'],2]返回['bb','dd']
def by_size(words,size)
单词中的单词:
if len(word)== size:
我不确定如何从这部分继续。建议将是一个很大的帮助。
解决方案
我会使用一个列表解析:
def by_size(words,size):
return [单词单词如果len(word)== size]
I'm trying to return elements of words that have length size. Words is a list and size is a positive integer here. The result should be like this.
by_size(['a','bb','ccc','dd'],2] returns ['bb','dd']
def by_size(words,size)
for word in words:
if len(word)==size:
I'm not sure how to continue from this part. Any suggestion would be a great help.
解决方案
I would use a list comprehension:
def by_size(words, size):
return [word for word in words if len(word) == size]
这篇关于python返回具有一定长度的列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文