python- return elements of list that have certain length
问题 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. 回答1: I would use a list comprehension: def by_size(words, size): return [word for word in words if len(word) == size] 回答2: return filter(lambda x: len