2

我想在函数中声明一条if语句:lambda

认为:

cells = ['Cat', 'Dog', 'Snake', 'Lion', ...]
result = filter(lambda element: if 'Cat' in element, cells)

是否可以将“猫”过滤掉result

4

3 回答 3

12

如果要过滤掉其中包含的所有字符串'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']
于 2013-07-26T01:53:21.390 回答
2

你不需要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 + 过滤器

于 2013-07-26T04:48:27.377 回答
2

表示可迭代的element元素。你只需要比较。

>>> cells = ['Cat', 'Dog', 'Snake', 'Lion']
>>> filter(lambda element: 'Cat' == element, cells)
['Cat']
>>> 

或者如果你想用来in测试元素是否包含某些东西,不要使用if. 单个if表达式是语法错误。

>>> filter(lambda element: 'Cat' in element, cells)
['Cat']
>>> 
于 2013-07-26T01:52:03.273 回答