我有一个字符串列表,我想删除列表中包含字符串的字符串excludeList。过滤器需要一个函数和一个列表,我如何“功能化”excluded not in
? excludeList类似于:["A2123", "B323", "C22"]
并且kolaDataList看起来像:["Very long string somethingsomething B323", "Lorem ipsum"]
,结果应为[Lorem ipsum]
for excluded in excludeList:
kolaDataList = filter((excluded not in), kolaDataList)
我想这可以在haskell中运行,但我如何在python中执行此操作?
答案 0 :(得分:3)
您可以使用lambda或匿名函数:
for excluded in excludeList:
kolaDataList = filter(lambda l: excluded not in l, kolaDataList)
或者,只需使用列表理解:
for excluded in excludeList:
kolaDataList = [l for l in kolaDataList if excluded not in l]
答案 1 :(得分:3)
您可以将此作为列表理解:
kolaDataList = [l for l in kolaDataList if excluded not in l]
答案 2 :(得分:1)
您必须构建自己的功能来过滤您的内容,例如:具有lambda
功能。让我们构建一个通用函数,根据您的条件过滤值:
generic_filter = lambda item, excludeList=[]: item not in excludeList
现在,您可以使用filter
调整此功能以与functools.partial
一起使用。
import functools
# This function will be used with specific exclude list you pass it
my_filter = functools.partial(generic_filter, excludeList=excludeList)
# Apply filter
result = filter(my_filter, kolaDataList)
创建中间通用功能的优点是您可以重复使用它来应用不同的排除列表。