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

后端 未结 5 899
一生所求
一生所求 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:22

    Assuming you want to use them later then returning them as a list is a good idea. Or just print them to terminal. It really depends on what you are aiming for. You can just go list (or whatever the variable name is).append within the if statement to do this.

    0 讨论(0)
  • 2020-11-30 14:32

    Do you mean this:

    In [1]: words = ['a', 'bb', 'ccc', 'dd']
    
    In [2]: result = [item for item in words if len(item)==2]
    
    In [3]: result
    Out[3]: ['bb', 'dd']
    
    0 讨论(0)
  • 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']

    0 讨论(0)
  • 2020-11-30 14:35

    I would use a list comprehension:

    def by_size(words, size):
        return [word for word in words if len(word) == size]
    
    0 讨论(0)
  • 2020-11-30 14:36
    return filter(lambda x: len(x)==size, words)
    

    for more info about the function, please see filter()

    0 讨论(0)
提交回复
热议问题