How to return elements from a list that have a certain length?

后端 未结 5 919
一生所求
一生所求 2020-11-30 14:14

I\'m trying to return words that have a specific length size.

The words is a list and size is a positive integer here. The result should be

5条回答
  •  青春惊慌失措
    2020-11-30 14:34

    def by_size(words,size):
        result = []
        for word in words:
            if len(word)==size:
                result.append(word)
        return result
    

    Now call the function like below

    desired_result = by_size(['a','bb','ccc','dd'],2)
    

    where desired_result will be ['bb', 'dd']

提交回复
热议问题