python- return elements of list that have certain length

偶尔善良 提交于 2019-11-28 03:29:52

问题


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(x)==size, words)

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




回答3:


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




回答4:


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



回答5:


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.



来源:https://stackoverflow.com/questions/26697601/python-return-elements-of-list-that-have-certain-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!