我想在函数中声明一条if
语句:lambda
认为:
cells = ['Cat', 'Dog', 'Snake', 'Lion', ...]
result = filter(lambda element: if 'Cat' in element, cells)
是否可以将“猫”过滤掉result
?
我想在函数中声明一条if
语句:lambda
认为:
cells = ['Cat', 'Dog', 'Snake', 'Lion', ...]
result = filter(lambda element: if 'Cat' in element, cells)
是否可以将“猫”过滤掉result
?
如果要过滤掉其中包含的所有字符串'cat'
,则只需使用
>>> cells = ['Cat', 'Dog', 'Snake', 'Lion']
>>> filter(lambda x: not 'cat' in x.lower(), cells)
['Dog', 'Snake', 'Lion']
如果您想保留'cat'
其中的内容,只需删除not
.
>>> filter(lambda x: 'cat' in x.lower(), cells)
['Cat']
您也可以在这里使用列表推导。
>>> [elem for elem in cells if 'cat' in elem.lower()]
['Cat']
你不需要if
,这里。您lambda
将返回一个布尔值,并且filter()
只会返回那些返回的lambda
元素True
。
看起来您正在尝试执行以下任一操作:
>>> filter(lambda cell: 'Cat' in cell , cells)
['Cat']
或者...
>>> filter(lambda cell: 'Cat' not in cell, cells)
['Dog', 'Snake', 'Lion', '...']
...我不知道是哪个。
请注意,这filter(function, iterable)
等效于[item for item in iterable if function(item)]
并且更常见(Pythonic)对此模式使用列表推导:
>>> [cell for cell in cells if 'Cat' in cell]
['Cat']
>>> [cell for cell in cells if 'Cat' not in cell]
['Dog', 'Snake', 'Lion', '...']
有关更多信息,请参阅列表过滤:列表理解与 lambda + 过滤器。
表示可迭代的element
元素。你只需要比较。
>>> cells = ['Cat', 'Dog', 'Snake', 'Lion']
>>> filter(lambda element: 'Cat' == element, cells)
['Cat']
>>>
或者如果你想用来in
测试元素是否包含某些东西,不要使用if
. 单个if
表达式是语法错误。
>>> filter(lambda element: 'Cat' in element, cells)
['Cat']
>>>