简体   繁体   中英

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

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 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]
return filter(lambda x: len(x)==size, words)

有关该功能的更多信息,请参阅filter()

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']
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']

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM