表达式模块错误“筛选器对象”

2024-04-25 17:59:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这个网站学习表达模块 http://www.thomas-cokelaer.info/tutorials/python/module_re.html

我做了9.1中的第一个练习

s = ['airplane', 'base', 'ALLIGATOR', 'Broad' ]

filter((lambda x: re.match(r'A', x)),s)

答案是['ALLIGATOR']

但我知道

^{pr2}$

我的回答不是['ALLIGATOR']

我使用的是python3.4.2 有什么问题吗?在


Tags: 模块reinfohttpbase网站htmlwww
1条回答
网友
1楼 · 发布于 2024-04-25 17:59:36

引用documentation

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

要获得这些元素,您需要一个循环或使用next

>>> next(filter(lambda x: re.match(r'A', x), s))
'ALLIGATOR'

或者

^{pr2}$

相关问题 更多 >