如何返回一定长度的字符串列表?

时间:2013-02-04 07:03:23

标签: python

我要做的是创建一个程序,返回一定长度的字符串列表。我有一个程序,但我觉得它非常关闭

def lett(lst,n):
res = []
for a in range(1,len(lst)):
               if a == n
                   res = lst[a]
return res

我想要的是获取列表并返回所有n长度的单词,如果我要做lett([“boo”,“hello”,“maybe”,“yes”,“nope”) ],)它会返回['boo','yes']

谢谢!

3 个答案:

答案 0 :(得分:2)

试试这个:

def lett(lst, n):
    return [x for x in lst if len(x) == n]

或者:

def lett(lst, n)
    return filter(lambda x: len(x) == n, lst)

答案 1 :(得分:2)

使用filter功能

def lett(lst, n):
    return filter(lambda x: len(x) == n, lst)

这将在Python 2中返回一个列表。如果您使用的是Python 3,它将返回一个filter对象,因此您可能希望将其转换为列表。

return list(filter(lambda x: len(x) == n, lst))

答案 2 :(得分:0)

def lett(lst, n):
    return [tmpStr for tmpStr in lst if len(tmpStr) == n]