python toolz - 组合方法(相对于函数)
python toolz - composing methods (in contrast to functions)
在 toolz 项目中,有没有像对待函数一样对待对象方法的方法,这样我就可以更好地编写、curry 等?
更好的意思是可读性和相似的性能
这是一个简单的例子:
# given a list strings (names),
l = ["Harry" ,
"Sally " ,
" bEn " ,
" feDDy " ]
# Lets pretend I want to apply a few simple string methods on each item in the
# list (This is just an example), and maybe replace as it's multi-airity.
# Traditional python list comprehension:
print([x.strip().lower().title().replace('H','T') for x in l ])
['Tarry', 'Sally', 'Ben', 'Feddy']
# my attempt, at toolz, same question with compose, curry,
# functools.partial.
from toolz.functoolz import pipe, thread_last
thread_last(l,
(map , str.strip),
(map , str.lower),
(map , str.title),
(map , lambda x: x.replace('H','T')), # any better way to do this?
# I wish i had function/method `str.replace(__init_value__, 'H', 'T')` where the
# `__init_value` is what I guess would go to the str constructor?
list,
print)
我不喜欢所有额外的 lambda...而且我无法想象那会好
为了表现。关于如何使用 toolz 使它变得更好的任何提示?
有了 operators
模块,我可以让大多数操作员不那么痛苦并省略
用于加法、减法等的 lambda。
python 的最新版本中是否有类似的方法调用?
请注意 x.replace(y, z)
确实是 str.replace(x, y, z)
。您可以使用 partial
是经常使用的特定替代品。
同样适用于其余的方法:如果您通过 class 访问一个方法,它是未绑定的,并且第一个参数 (self
) 是一个函数的普通参数。周围没有魔法。 (部分应用实例方法,将它们的 self
值锁定到实例。)
因此,我会冒险 thread_last(l, (map, pipe(str.strip, str.lower, str.title))
对每个字符串元素应用三个函数。
(如果您在 Python 中喜欢 FP,请查看 http://coconut-lang.org/)
在 toolz 项目中,有没有像对待函数一样对待对象方法的方法,这样我就可以更好地编写、curry 等?
更好的意思是可读性和相似的性能
这是一个简单的例子:
# given a list strings (names),
l = ["Harry" ,
"Sally " ,
" bEn " ,
" feDDy " ]
# Lets pretend I want to apply a few simple string methods on each item in the
# list (This is just an example), and maybe replace as it's multi-airity.
# Traditional python list comprehension:
print([x.strip().lower().title().replace('H','T') for x in l ])
['Tarry', 'Sally', 'Ben', 'Feddy']
# my attempt, at toolz, same question with compose, curry,
# functools.partial.
from toolz.functoolz import pipe, thread_last
thread_last(l,
(map , str.strip),
(map , str.lower),
(map , str.title),
(map , lambda x: x.replace('H','T')), # any better way to do this?
# I wish i had function/method `str.replace(__init_value__, 'H', 'T')` where the
# `__init_value` is what I guess would go to the str constructor?
list,
print)
我不喜欢所有额外的 lambda...而且我无法想象那会好 为了表现。关于如何使用 toolz 使它变得更好的任何提示?
有了 operators
模块,我可以让大多数操作员不那么痛苦并省略
用于加法、减法等的 lambda。
python 的最新版本中是否有类似的方法调用?
请注意 x.replace(y, z)
确实是 str.replace(x, y, z)
。您可以使用 partial
是经常使用的特定替代品。
同样适用于其余的方法:如果您通过 class 访问一个方法,它是未绑定的,并且第一个参数 (self
) 是一个函数的普通参数。周围没有魔法。 (部分应用实例方法,将它们的 self
值锁定到实例。)
因此,我会冒险 thread_last(l, (map, pipe(str.strip, str.lower, str.title))
对每个字符串元素应用三个函数。
(如果您在 Python 中喜欢 FP,请查看 http://coconut-lang.org/)