繁体   English   中英

将此过滤器语句转换为列表理解

[英]Converting this filter statement to list comprehension

我有这个过滤器语句:

s = [['hello', 'there', 'friend', '.'], ['i', 'am', 'max', ',doe', '"']]
t = [filter(lambda x: len(x) > 2, string) for string in s]

这将产生我想要的结果,但我需要t是列表,而不是过滤对象的列表清单。 如何将其转换为列表理解?

谢谢。

如果您不想使用filter() ,可以尝试以下操作:

m = [[e for e in l if len(e) > 2] for l in s]
print m

输出:

[['hello', 'there', 'friend'], ['max', ',doe']]

编辑:

请记住,上面的代码等效于:

result = []

for l in s:
    sub_result = []
    for e in l:
        if len(e) > 2:
            sub_result.append(e)
    result.append(sub_result)

print result

过滤器解决方案:

t = [list(filter(lambda x: len(x) > 2, string)) for string in s]

filter对象仅存在于Python 3中,因此您需要使用内置的list()函数将其转换为list类型。 例如:

>>> t = [list(filter(lambda x: len(x) > 2, string)) for string in s]
>>> t
[['hello', 'there', 'friend'], ['max', ',doe']]
>>> 

清单理解解决方案:

>>> t = [[x for x in string if len(x) > 2] for string in s]
>>> t
[['hello', 'there', 'friend'], ['max', ',doe']]
>>>     

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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