如何从列表中返回具有一定长度的元素? [英] How to return elements from a list that have a certain length?

查看:47
本文介绍了如何从列表中返回具有一定长度的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试返回具有特定长度大小的单词.

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

这里的 words 是一个列表,而 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.

推荐答案

我会使用列表理解:

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

这篇关于如何从列表中返回具有一定长度的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆