前段时间我查看了Haskell文档,发现它的功能组合运算符非常好.所以我实现了这个小装饰:
from functools import partial
class _compfunc(partial):
def __lshift__(self, y):
f = lambda *args, **kwargs: self.func(y(*args, **kwargs))
return _compfunc(f)
def __rshift__(self, y):
f = lambda *args, **kwargs: y(self.func(*args, **kwargs))
return _compfunc(f)
def composable(f):
return _compfunc(f)
@composable
def f1(x):
return x * 2
@composable
def f2(x):
return x + 3
@composable
def f3(x):
return (-1) * x
@composable
def f4(a):
return a + [0]
print (f1 >> f2 >> f3)(3) #-9
print (f4 >> f1)([1, 2]) #[1, 2, 0, 1, 2, …Run Code Online (Sandbox Code Playgroud) 是否有任何非显式for方法可以n在对象上调用成员时间?
我正在考虑一些map/reduce/lambda方法,但我想不出办法做到这一点 - 如果有可能的话.
只是添加上下文,我正在使用BeautifulSoup,我正在从html表中提取一些元素; 我提取了一些元素,然后是最后一个元素.
因为我有:
# First value
print value.text
# Second value
value = value.nextSibling
print value.text
# Ninth value
for i in xrange(1, 7):
value = value.nextSibling
print value.text
Run Code Online (Sandbox Code Playgroud)
我想知道是否有任何lambda方法 - 或其他 - 允许我这样做:
# Ninth value
((value = value.nextSibling) for i in xrange(1, 7))
print value.text
Run Code Online (Sandbox Code Playgroud)
PS:不,这种for方法没有任何问题,除了我真的很喜欢单线解决方案,这在我的代码中非常适合.