嗨,伙计们,我正在尝试编写一个使用函数列表和整数列表的代码,并且只返回函数列表中至少有 1 个 true 的函数,如下所示:
tuple(lambda func,data:filter(lambda x:map(lambda y:y(x)==true,func),data))
func=(lambda x: x>3,lambda x: x%2==0)
data=(1,2,3,4,5,6,7,8,9,10)
所以列表应该返回 4,6,8,10 但它返回整个列表,有人知道为什么吗?
PS 我知道它可以用不同的方式很容易地完成,但它是一个 lambda 练习。
您可以使用如下表达式:
tuple(filter(lambda x: any(filter(lambda f: f(x), func)), data))
所以,
In [17]: func=(lambda x: x>3,lambda x: x%2==0)
...: data=(1,2,3,4,5,6,7,8,9,10)
...:
...:
In [18]: tuple(filter(lambda x: any(filter(lambda f: f(x), func)), data))
Out[18]: (2, 4, 5, 6, 7, 8, 9, 10)
另请注意,您的表达式会引发 a TypeError
,所以我不知道您对返回整个列表的意思是什么。
使用以下内容可能更具可读性:
In [23]: tuple(
...: x for x in data
...: if any(f(x) for f in func)
...: )
Out[23]: (2, 4, 5, 6, 7, 8, 9, 10)
或者没有any
(一个荒谬的约束)
In [29]: tuple(filter(lambda x: tuple(filter(None, map(lambda f: f(x), func))), data))
Out[29]: (2, 4, 5, 6, 7, 8, 9, 10)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句